Django rest framework + Vue简单示例

一、创建Vue项目

修改源:npm config set registry https://registry.npm.taobao.org         (建议修改)

创建脚手架:vue init webpack Vue项目名称

基本插件:

axios,发送Ajax请求
vuex,保存所有组件共用的变量
vue-cookies,操作cookie

二、流程

vue项目基本目录结构

1.创建脚手架

vue init webpack Vue项目名称

运行 npm run dev

2.App.Vue中

# 用于点击查看组件
<router-link to="/index">首页</router-link>

# 组件显示的位置
<router-view/>

3.写路由

写在route/index.js中

import Vue from ‘vue‘
import Router from ‘vue-router‘
import HelloWorld from ‘@/components/HelloWorld‘
import index from ‘@/components/Index‘
import Cource from ‘@/components/Cource‘
import Xw from ‘@/components/Xw‘
import Login from ‘@/components/Login‘
import CourseDetail from ‘@/components/CourseDetail‘

Vue.use(Router);

export default new Router({
  routes: [
    {
      path: ‘/‘,
      name: ‘HelloWorld‘,
      component: HelloWorld
    },
    {
      path: ‘/index‘,
      name: ‘index‘,
      component: index
    },
    {
      path: ‘/cource‘,
      name: ‘Cource‘,
      component: Cource
    },
    {
      path: ‘/xw‘,
      name: ‘Xw‘,
      component: Xw
    },
    {
      path: ‘/login‘,
      name: ‘Login‘,
      component: Login
    },
     {
      path: ‘/course-detail/:id/‘,
      name: ‘CourseDetail‘,
      component: CourseDetail
    }
  ],
  mode: ‘history‘
})

index.js

注意:

我们访问的时候url一般会带有‘#’,如果不想有,在路由后面加上  mode: ‘history‘

如果想url中想传参:

 {
      path: ‘/course-detail/:id/‘,
      name: ‘CourseDetail‘,
      component: CourseDetail
    }

4.写组件

组件写在src/components下

<template>
  <div class="hello">
   <h1>登录</h1>
    <input type="text"  v-model="username"><br>
    <input type="text"   v-model="password"><br>
    <a type="button" @click="doLogin">提交</a>
  </div>
</template>

<script>
export default {
  name: ‘HelloWorld‘,
  data () {
    return {
      username: ‘‘,
      password:‘‘,
    }
  },
  methods:{
    doLogin(){
      var that = this;
      this.$axios.request({
        url:‘http://127.0.0.1:8000/login/‘,
        method:‘POST‘,
        data:{
          username:this.username,
          password:this.password
        },
        responseType:‘json‘
      }).then(function (response) {
        console.log(response.data);
        that.$store.commit(‘saveToken‘,response.data);
        // 重定向到index
        that.$router.push(‘/index‘)
      })

    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

5.类似与ajax的请求ajax请求:axios

下载:npm install axios

首先必须在main.js中导入

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from ‘vue‘
import App from ‘./App‘
import router from ‘./router‘
import axios from ‘axios‘
import store from ‘./store/store‘

Vue.prototype.$axios = axios;

Vue.config.productionTip = false;

/* eslint-disable no-new */
new Vue({
  el: ‘#app‘,
  store,
  router,
  components: { App },
  template: ‘<App/>‘
});

main.js

import axios from ‘axios‘
Vue.prototype.$axios = axios

使用:

methods:{
    doLogin(){
      var that = this;
      this.$axios.request({
        url:‘http://127.0.0.1:8000/login/‘,
        method:‘POST‘,
        data:{
          username:this.username,
          password:this.password
        },
        responseType:‘json‘
      }).then(function (response) {
        console.log(response.data);
        that.$store.commit(‘saveToken‘,response.data);
        // 重定向到index
        that.$router.push(‘/index‘)
      })

    }
  }

重定向: that.$router.push(‘/index‘)

6.vuex的使用

下载:npm install vuex 

1.在src目录下创建store/store.js

import Vue from ‘vue‘
import Vuex from ‘vuex‘
import Cookie from ‘vue-cookies‘

Vue.use(Vuex);

export default new Vuex.Store({
  // 组件中通过 this.$store.state.username 调用
  state: {
    username: Cookie.get(‘username‘),
    token: Cookie.get(‘token‘)
  },
  mutations: {
    // 组件中通过 this.$store.commit(参数)  调用
    saveToken: function (state, data) {
      state.username = data.username;
      state.token = data.token;
      Cookie.set(‘username‘, data.username, ‘20min‘);
      Cookie.set(‘token‘, data.token, ‘20min‘)

    },
    clearToken: function (state) {
      state.username = null;
      state.token = null;
      Cookie.remove(‘username‘);
      Cookie.remove(‘token‘)
    }
  }
})

store.js

2.在main.js中导入store

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from ‘vue‘
import App from ‘./App‘
import router from ‘./router‘
import axios from ‘axios‘
import store from ‘./store/store‘ //vuex

Vue.prototype.$axios = axios;

Vue.config.productionTip = false;

/* eslint-disable no-new */
new Vue({
  el: ‘#app‘,
  store,   //vuex
  router,
  components: { App },
  template: ‘<App/>‘
});

main.js

7.vue-cookies 的使用

下载:npm install vue-cookies 

cookie的使用:

import Vue from ‘vue‘
import Vuex from ‘vuex‘
import Cookie from ‘vue-cookies‘

Vue.use(Vuex);

export default new Vuex.Store({
  // 组件中通过 this.$store.state.username 调用
  state: {
    username: Cookie.get(‘username‘),
    token: Cookie.get(‘token‘)
  },
  mutations: {
    // 组件中通过 this.$store.commit(参数)  调用
    saveToken: function (state, data) {
      state.username = data.username;
      state.token = data.token;
      Cookie.set(‘username‘, data.username, ‘20min‘);
      Cookie.set(‘token‘, data.token, ‘20min‘)

    },
    clearToken: function (state) {
      state.username = null;
      state.token = null;
      Cookie.remove(‘username‘);
      Cookie.remove(‘token‘)
    }
  }
})

store.js

8.router-link参数的常见用法

<router-link :to="{‘path‘:‘/course-detail/‘+item.id }"{{item.name}}</router-link>
<router-link to="/index">首页</router-link>

9. 获取传过来的参数

this.$route.params.id

10.重定向

this.$router.push(‘/index‘)

示例:

前端vue部分:

点击查看组件

<template>
  <div id="app">
    <router-link to="/index">首页</router-link>
    <router-link to="/cource">课程</router-link>
    <router-link to="/xw">学位</router-link>
    <div>
          <div v-if="this.$store.state.username">
          <a>{{ this.$store.state.username }}</a>
          <a @click="logout">注销</a>
          </div>
          <router-link v-else to="/login">登录</router-link>
        </div>
    <router-view/>
  </div>
</template>

<script>
export default {
  name: ‘App‘,
  methods:{
    logout(){
      this.$store.state.username = ‘‘;
      this.$store.state.token = ‘‘
    }
  }
}
</script>

<style>
/*#app {*/
  /*font-family: ‘Avenir‘, Helvetica, Arial, sans-serif;*/
  /*-webkit-font-smoothing: antialiased;*/
  /*-moz-osx-font-smoothing: grayscale;*/
  /*text-align: center;*/
  /*color: #2c3e50;*/
  /*margin-top: 60px;*/
/*}*/
</style>

App.vue

组件

<template>
  <div class="hello">
   <h1>登录</h1>
    <input type="text"  v-model="username"><br>
    <input type="text"   v-model="password"><br>
    <a type="button" @click="doLogin">提交</a>
  </div>
</template>

<script>
export default {
  name: ‘HelloWorld‘,
  data () {
    return {
      username: ‘‘,
      password:‘‘,
    }
  },
  methods:{
    doLogin(){
      var that = this;
      this.$axios.request({
        url:‘http://127.0.0.1:8000/login/‘,
        method:‘POST‘,
        data:{
          username:this.username,
          password:this.password
        },
        responseType:‘json‘
      }).then(function (response) {
        console.log(response.data);
        that.$store.commit(‘saveToken‘,response.data);
        // 重定向到index
        that.$router.push(‘/index‘)
      })

    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

Login.vue

<template>
  <div class="hello">
   <h1>首页</h1>
  </div>
</template>

<script>
export default {
  name: ‘HelloWorld‘,
  data () {
    return {
      msg: ‘Welcome to Your Vue.js App‘
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

index.vue

<template>
  <div class="hello">
       <ul>
      <li v-for="item in courseList" >
        <router-link :to="{‘path‘:‘/course-detail/‘+item.id }">{{item.name}}</router-link>
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  name: ‘HelloWorld‘,
  data () {
    return {
      courseList: ‘‘
    }
  },
  mounted:function () {
     this.initCourses()
  },
   methods: {
    initCourses:function () {
      var that = this;
      this.$axios.request({
        url: ‘http://127.0.0.1:8000/courses/‘,
        method: ‘GET‘
      }).then(function (response) {
        that.courseList = response.data.courseList
      })
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

Cource.vue

<template>
  <div>
      <div>课程详细</div>
      <h1>{{title}}</h1>
      <h1>{{summary}}</h1>

  </div>
</template>

<script>
export default {
  data () {
    return {
      title:‘‘,
      summary:‘‘,
    }
  },
  mounted:function () {
    this.initCourseDetail()
  },
  methods:{
    initCourseDetail (){
      var nid = this.$route.params.id;
      var that = this;
      var url = ‘http://127.0.0.1:8000/courses/‘ + nid+‘.json‘;
      this.$axios.request({
        url: url,
        method:‘GET‘,
        responseType:‘json‘
      }).then(function (response) {
        console.log(response);
        that.title = response.data.title;
        that.summary = response.data.summary
      })
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>

CourceDetail.vue

路由:

import Vue from ‘vue‘
import Router from ‘vue-router‘
import HelloWorld from ‘@/components/HelloWorld‘
import index from ‘@/components/Index‘
import Cource from ‘@/components/Cource‘
import Xw from ‘@/components/Xw‘
import Login from ‘@/components/Login‘
import CourseDetail from ‘@/components/CourseDetail‘

Vue.use(Router);

export default new Router({
  routes: [
    {
      path: ‘/‘,
      name: ‘HelloWorld‘,
      component: HelloWorld
    },
    {
      path: ‘/index‘,
      name: ‘index‘,
      component: index
    },
    {
      path: ‘/cource‘,
      name: ‘Cource‘,
      component: Cource
    },
    {
      path: ‘/xw‘,
      name: ‘Xw‘,
      component: Xw
    },
    {
      path: ‘/login‘,
      name: ‘Login‘,
      component: Login
    },
     {
      path: ‘/course-detail/:id/‘,
      name: ‘CourseDetail‘,
      component: CourseDetail
    }
  ],
  mode: ‘history‘
})

index.js

保存全局使用的变量

import Vue from ‘vue‘
import Vuex from ‘vuex‘
import Cookie from ‘vue-cookies‘

Vue.use(Vuex);

export default new Vuex.Store({
  // 组件中通过 this.$store.state.username 调用
  state: {
    username: Cookie.get(‘username‘),
    token: Cookie.get(‘token‘)
  },
  mutations: {
    // 组件中通过 this.$store.commit(参数)  调用
    saveToken: function (state, data) {
      state.username = data.username;
      state.token = data.token;
      Cookie.set(‘username‘, data.username, ‘20min‘);
      Cookie.set(‘token‘, data.token, ‘20min‘)

    },
    clearToken: function (state) {
      state.username = null;
      state.token = null;
      Cookie.remove(‘username‘);
      Cookie.remove(‘token‘)
    }
  }
})

store.js

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from ‘vue‘
import App from ‘./App‘
import router from ‘./router‘
import axios from ‘axios‘
import store from ‘./store/store‘ //vuex

Vue.prototype.$axios = axios;

Vue.config.productionTip = false;

/* eslint-disable no-new */
new Vue({
  el: ‘#app‘,
  store,   //vuex
  router,
  components: { App },
  template: ‘<App/>‘
});

main.js

后端restframwork部分

"""luffyweb URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r‘^$‘, views.home, name=‘home‘)
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r‘^$‘, Home.as_view(), name=‘home‘)
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r‘^blog/‘, include(‘blog.urls‘))
"""
from django.conf.urls import url
from django.contrib import admin
from api import views

urlpatterns = [
    url(r‘^admin/‘, admin.site.urls),
    url(r‘^login/‘, views.LoginView.as_view()),
    url(r‘^courses/$‘, views.CoursesView.as_view()),
    url(r‘^courses/(?P<pk>\d+)\.(?P<format>[a-z0-9]+)$‘, views.CoursesView.as_view()),
]

urls

from django.http import JsonResponse
from django.shortcuts import render,HttpResponse
from rest_framework.views import APIView

# Create your views here.

class LoginView(APIView):
    def get(self,request,*args,**kwargs):
        ret = {
            ‘code‘: 1000,
            ‘data‘: ‘老男孩‘
        }
        response = JsonResponse(ret)
        response[‘Access-Control-Allow-Origin‘] = "*"
        return response

    def post(self,request,*args,**kwargs):

        print(request.POST)
        ret = {
            ‘code‘:1000,
            ‘username‘:‘老男孩‘,
            ‘token‘:‘71ksdf7913knaksdasd7‘,
        }
        response = JsonResponse(ret)
        response[‘Access-Control-Allow-Origin‘] = "*"
        return response

    def options(self, request, *args, **kwargs):
        # self.set_header(‘Access-Control-Allow-Origin‘, "http://www.xxx.com")
        # self.set_header(‘Access-Control-Allow-Headers‘, "k1,k2")
        # self.set_header(‘Access-Control-Allow-Methods‘, "PUT,DELETE")
        # self.set_header(‘Access-Control-Max-Age‘, 10)

        response = HttpResponse()
        response[‘Access-Control-Allow-Origin‘] = ‘*‘
        response[‘Access-Control-Allow-Headers‘] = ‘*‘
        #response[‘Access-Control-Allow-Methods‘] = ‘PUT‘
        return response

class CoursesView(APIView):
    def get(self, request, *args, **kwargs):
        pk = kwargs.get(‘pk‘)
        if pk:
            ret = {
                ‘title‘: "标题标题标题",
                ‘summary‘: ‘老师,太饿了。怎么还不下课‘
            }
        else:
            ret = {
                ‘code‘: 1000,
                ‘courseList‘: [
                    {"name": ‘21天学会Pytasdfhon‘, ‘id‘: 1},
                    {"name": ‘23天学会Pytasdfhon‘, ‘id‘: 2},
                    {"name": ‘24天学会Pytasdfhon‘, ‘id‘: 3},
                ]
            }
        response = JsonResponse(ret)
        response[‘Access-Control-Allow-Origin‘] = "*"
        return response

views

原文地址:https://www.cnblogs.com/mjc69213/p/9937445.html

时间: 2024-07-31 16:09:32

Django rest framework + Vue简单示例的相关文章

Django REST framework+Vue 打造生鲜超市(一)

一.项目介绍 1.1.掌握的技术 Vue + Django Rest Framework 前后端分离技术 彻底玩转restful api 开发流程 Django Rest Framework 的功能实现和核心源码分析 Sentry 完成线上系统的错误日志的监控和告警 第三方登录和支付宝支付的集成 本地调试远程服务器代码的技巧 1.2.课程系统构成 vue前端项目 django rest framework 系统实现前台功能 xadmin后台管理系统 vue部分: API 接口 Vue 组件 与a

Django REST framework+Vue 打造生鲜超市(五)

六.商品类别数据展示 6.1. 商品类别数据接口 (1)商品分类有两个接口: 一种是全部分类:一级二级三级 一种是某一类的分类以及商品详细信息: 开始写商品分类的接口 (2)序列化 给分类添加三级分类的serializer goods/serializers.py from rest_framework import serializers from .models import Goods,GoodsCategory class CategorySerializer3(serializers.

Django REST framework+Vue 打造生鲜超市(九)

十.购物车.订单管理和支付功能 10.1.添加商品到购物车 (1)trade/serializer.py # trade/serializer.py __author__ = 'derek' from .models import ShoppingCart from rest_framework import serializers from goods.models import Goods class ShopCartSerializer(serializers.Serializer): #

Django REST framework+Vue 打造生鲜超市(十三)

十四.social_django 集成第三方登录 14.1.申请应用 进入微博开放平台,首先要经过认证,然后才可以创建应用 地址:http://open.weibo.com/authentication 创建应用 写上应用的名字,创建好后,会有个“App Key”,这个非常重要  OAuth2.0 授权设置 正常情况下,必须经过审核才可以让第三方登录,我们可以先用测试模式来完成. (1)添加测试用户,可以测试登录 (2)高级信息  14.2.第三方登录 我们用social_django第三方库来

django admin 导出数据简单示例

借鉴博客:https://www.lijinlong.cc/django/djxs/2101.html 具体代码实现: class TipReport(admin.ModelAdmin): actions = ['saveexcel'] list_display = ('tiptype', 'enabled', 'get_tag','get_content') search_fields = ('get_tag', 'tiptype') list_per_page = 500 def get_t

Django REST framework+Vue 打造生鲜超市(三)

四.xadmin后台管理 4.1.xadmin添加富文本插件 (1)xadmin/plugins文件夹下新建文件ueditor.py 代码如下: # xadmin/plugins/ueditor.py import xadmin from xadmin.views import BaseAdminPlugin, CreateAdminView, ModelFormAdminView, UpdateAdminView from DjangoUeditor.models import UEditor

Django REST framework+Vue 打造生鲜超市(二)

三.Models设计 3.1.项目初始化 (1)进虚拟环境下安装 django2.0.2 djangorestframework和相关依赖mark,filter pillow  图片处理 pip install djangorestframework pip install -i https://pypi.douban.com/simple django==2.0.2 pip install markdown pip install django-filter pip install pillo

【Django】Django REST Framework简单教程

Django REST Framework使用案例和教程 什么是Django REST Framework?简单说就是一款快速构建REST风格API的框架.能够以很少的代码和很简单的方式在Django项目中构建符合REST风格的API.十分适合Django框架的后端的编写 本文参考 https://blog.csdn.net/weixin_40193776/article/details/81210215,教程原文非常详细,还带图片.本文做了顺序上的修改以符合从无到有建立REST Framewo

Python前后端分离开发Vue+Django REST framework实战

链接:https://pan.baidu.com/s/1YNIw7ayEvRfU9Og4zv97iA 提取码:加Q:1642261812  V信:SH66668888QH 获取 第1章 课程介绍 介绍课程目标.通过课程能学习到的内容.和系统开发前需要具备的知识 1-1 课程导学 第2章 开发环境搭建 介绍系统开发所需的开发环境的搭建, 包括前后端开发所需要的IDE. mysql.navicat.nodejs.cnpm的配置等, 还介绍了如何配置python虚拟环境 2-1 pycharm的安装和