目录
一、vue配置和组件
1、创建脚手架
2、运行
3、显示组件
4、写路由
5、写Login组件
6、发送ajax请求:axios
7、vuex:保存所有组件共用的变量
二、前端代码:
index.html
App.vue
router\index.js
组件components
保存全局使用的变量store
三、Django后端代码:
urls.py:
views.py:
安装vue前端框架:
修改源:
npm config set registry https://registry.npm.taobao.org
创建脚手架:
vue init webpack Vue项目名称
#记得把route的这个设置为yes,其他的设置为no 比如: Install vue-router? Yes
插件:
axios,发送Ajax请求
vuex,保存所有组件共用的变量
vue-cookies,操作cookie
二、流程详细
#可以用淘宝源来下载,这样下载的快
npm config set registry https://registry.npm.taobao.org
vue init webpack
#把route的那一个设置为yes,其他的设置为no
cd Vue项目名称
npm run dev
# 用于点击查看组件
# 组件显示的位置
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Index from '@/components/Index'
import Login from '@/components/Login'
import Micro from '@/components/Micro'
import News from '@/components/News'
import Course from '@/components/Course'
import CourseDetail from '@/components/CourseDetail'
import NotFound from '@/components/NotFound'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
},
{
path: '/index',
name: 'index',
component: Index
},
{
path: '/login',
name: 'Login',
component: Login
},
{
path: '/course',
name: 'Course',
component: Course
},
{
path: '/course-detail/:id/',
name: 'CourseDetail',
component: CourseDetail
},
{
path: '/micro/',
name: 'Micro',
component: Micro
},
{
path: '/course-detail/:id/',
name: 'CourseDetail',
component: CourseDetail
},
{
path: '/news/',
name: 'News',
component: News
},
{
path: '*',
component: NotFound
}
],
mode:'history'
})
使用路由
# 定义路由
{
path: '/course-detail/:id/',
name: 'courseDetail',
component: CourseDetail
},
{
path: '/login',
name: 'login',
component: Login
},
{
path: '*',
component: NotFound
}
# router-link参数
{{item.name}}
首页
# 获取传过来的参数
this.$route.params.id
# 重定向
this.$router.push('/index')
注意:
如果不想在url显示#,可以在路由里面加上这样一个参数
mode: 'history'
登录页面
用户名:
密码:
#发送ajax请求需要安装axios组件
npm install axios
在main.js导入中axios:
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store/store' //
import axios from 'axios' // 要是用axios,就得先导入
Vue.prototype.$axios = axios //注册,以后就可以用$axios来定义了
Vue.config.productionTip = false
axios组件使用:
this.$axios.request({ //发送axios请求
url:'http://127.0.0.1:8000/login/', //请求路径
method:"POST",//请求方式
data:{ //要发送 的数据
username:this.username,
password:this.password
},
responseType:'json' //期望返回的类型是json的格式
}).then(function (response) { //把返回的结果交给回调函数处理
//登录成功之后,找到全局变量,把用户名和token赋值到其中
that.$store.commit('saveToken',response.data);
//重定向(登录成功之后让跳转到index页面)
that.$router.push('/index')
//为什么不直接用this呢?这里的this代表的是$axios,用that他代指的是整个Vue对象
})
安装
npm install vuex
如果想用vuex需要做这么几件事:
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) { //存放用户名和token的函数
state.username = data.username //data代指从后端返回过来的数据
state.token = data.token
Cookie.set('username',data.username,'20min') //把用户名和token存放到cookie中
Cookie.set('token',data.token,'20min')
},
//清空token和cookie
clearToken:function (state) {
state.username=null
state.token= null
Cookie.remove('username')
Cookie.remove('token')
}
}
})
安装
npm install vue-cookies
Cookie.get('username')
Cookie.set('username', data.username, '20min')
Cookie.remove('username')
三、代码实现
s6vue
// 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 store from './store/store' //
import axios from 'axios' // 要是用axios,就得先导入
Vue.prototype.$axios = axios //注册,以后就可以用$axios来定义了
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
store,
router,
components: { App },
template: ' '
})
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Index from '@/components/Index'
import Login from '@/components/Login'
import Micro from '@/components/Micro'
import News from '@/components/News'
import Course from '@/components/Course'
import CourseDetail from '@/components/CourseDetail'
import NotFound from '@/components/NotFound'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
},
{
path: '/index',
name: 'index',
component: Index
},
{
path: '/login',
name: 'Login',
component: Login
},
{
path: '/course',
name: 'Course',
component: Course
},
{
path: '/course-detail/:id/',
name: 'CourseDetail',
component: CourseDetail
},
{
path: '/micro/',
name: 'Micro',
component: Micro
},
{
path: '/course-detail/:id/',
name: 'CourseDetail',
component: CourseDetail
},
{
path: '/news/',
name: 'News',
component: News
},
{
path: '*',
component: NotFound
}
],
mode:'history'
})
components\Index.vue:
{{ msg }}
components\Login.vue:
登录页面
用户名:
密码:
components\Course.vue:
-
{{item.name}}
components\CourseDetail.vue:
课程详细
{{ title }}
{{ summary }}
components\Micro.vue:
欢迎报名学位课
components\News.vue:
深科技
components\NotFound.vue:
找不到页面
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) { //存放用户名和token的函数
state.username = data.username //data代指从后端返回过来的数据
state.token = data.token
Cookie.set('username',data.username,'20min') //把用户名和token存放到cookie中
Cookie.set('token',data.token,'20min')
},
//清空token和cookie
clearToken:function (state) {
state.username=null
state.token= null
Cookie.remove('username')
Cookie.remove('token')
}
}
})
"""vue和restful配合 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 . import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^login/', views.LoginView.as_view()),
url(r'^course/$', views.CourseView.as_view()),
url(r'^course/(?P\d+)\.(?P[a-z-9]+)$', views.CourseView.as_view()),
]
rom django.shortcuts import render,HttpResponse
from rest_framework.views import APIView
from rest_framework.response import Response
from django.http import JsonResponse
class LoginView(APIView):
def get(self,request,*args,**kwargs):
ret = {
'code':111,
'data':'在知识的海洋里一路向前'
}
response = JsonResponse(ret)
response['Access-Control-Allow-Origin']='*'
return response
def post(self,request,*args,**kwargs):
print(request.body) #在body里面有值
print(request.POST) #在post里面是没有值的
ret = {
'code':1000,
'username':'hc',
'token':'sdswr3fdfsdfdxqw2fgh',
}
response = JsonResponse(ret)
response['Access-Control-Allow-Origin'] = "*"
return response
def options(self, request, *args, **kwargs):
response = HttpResponse()
response['Access-Control-Allow-Origin'] = '*'
response['Access-Control-Allow-Headers'] = '*'
# response['Access-Control-Allo w-Methods'] = 'PUT'
return response
class CourseView(APIView):
def get(self,request,*args,**kwargs):
print(args,kwargs)
pk = kwargs.get('pk')
if pk:
print(kwargs.get('pk'))
ret = {
'title': "标题标题标题",
'summary': '老师,太饿了。怎么还不下课'
}
else:
ret = {
'code':1000,
'courseList':[
{'name':'人生苦短,来学Python','id':1},
{'name':'32天学会java,欢迎报名','id':2},
{'name':'人工智能即将统领世界...','id':3},
]
}
response= JsonResponse(ret)
response['Access-Control-Allow-Origin'] = '*'
return response