簡(jiǎn)單回顧vue
首先強(qiáng)調(diào):
修改源:
npm config set registry https://registry.npm.taobao.org
創(chuàng)建腳手架:
vue init webpack Vue項(xiàng)目名稱
#記得把route的這個(gè)設(shè)置為yes,其他的設(shè)置為no 比如: Install vue-router? Yes
插件:
axios滩报,發(fā)送Ajax請(qǐng)求
vuex锅知,保存所有組件共用的變量
vue-cookies,操作cookie
流程詳細(xì)
1脓钾、創(chuàng)建腳手架
#可以用淘寶源來下載售睹,這樣下載的快
npm config set registry https://registry.npm.taobao.org
vue init webpack
#吧route的那一個(gè)設(shè)置為yes,其他的設(shè)置為no
2、運(yùn)行
cd Vue項(xiàng)目名稱
npm run dev
3可训、顯示組件
# 用于點(diǎn)擊查看組件
<router-link to="/index">首頁(yè)</router-link>
# 組件顯示的位置
<router-view/>
4昌妹、路由配置
index.js
import Vue from 'vue'
import Router from 'vue-router'
import Index from '@/components/Index'
import Login from '@/components/Login'
import Course from '@/components/Course'
import Micro from '@/components/Micro'
import News from '@/components/News'
import CourseDetail from '@/components/CourseDetail'
import NotFound from '@/components/NotFound'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'index',
component: Index
},
{
path: '/index',
name: 'index',
component: Index
},
{
path: '/course',
name: 'course',
component: Course
},
{
path: '/course-detail/:id/',
name: 'courseDetail',
component: CourseDetail
},
{
path: '/micro',
name: 'micro',
component: Micro
},
{
path: '/news',
name: 'news',
component: News
},
{
path: '/login',
name: 'login',
component: Login
},
{
path: '*',
component: NotFound
}
],
mode: 'history'
})
# 定義路由
{
path: '/course-detail/:id/',
name: 'courseDetail',
component: CourseDetail
},
{
path: '/login',
name: 'login',
component: Login
},
{
path: '*',
component: NotFound
}
# router-link參數(shù)
<router-link :to="{'path':'/course-detail/'+item.id }">{{item.name}}</router-link>
<router-link to="/index">首頁(yè)</router-link>
# 獲取傳過來的參數(shù)
this.$route.params.id
# 重定向
this.$router.push('/index')
注意
我們?cè)L問的時(shí)候url一般會(huì)帶有‘#’,如果不想有,在路由后面加上 mode: 'history'
5握截、寫組件
組件寫在src/components下
<template>
<div>
<h1>登錄頁(yè)面</h1>
<div>
<input type="text" v-model="username" placeholder="用戶名">
<input type="text" v-model="password" placeholder="密碼">
<a @click="doLogin">提交</a>
</div>
</div>
</template>
<script>
export default {
# 定義局部字段
data () {
return {
username: '',
password: ''
}
},
# 加載時(shí)執(zhí)行
mounted:function(){
},
# 定義局部方法
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)
// 找到全局變量飞崖,把用戶名和token賦值到其中。
that.$store.commit('saveToken',response.data)
// 重定向到index
that.$router.push('/index')
})
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
6谨胞、發(fā)送ajax請(qǐng)求:axios
#發(fā)送ajax請(qǐng)求需要安裝axios組件
npm install axios
npm install axios
main.js
import Vue from 'vue'
import App from './App'
import router from './router'
import axios from 'axios'
Vue.prototype.$axios = axios
Vue.config.productionTip = false
...
組件使用:
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.$router.push('/index')
})
PS:重定向 that.$router.push('/index')
7固歪、vuex:保存所有組件共用的變量
安裝
npm install vuex
具體步驟:
a、先創(chuàng)建一個(gè)文件夾,store----store.js
b牢裳、要先使用就先導(dǎo)入
c逢防、實(shí)例化一個(gè)對(duì)象,并且讓別人可以用
d蒲讯、這樣每一個(gè)組件都可以用username和token了
npm install vuex
main.js
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/>'
})
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 調(diào)用
state: {
username: Cookie.get('username'),
token: Cookie.get('token')
},
mutations: {
// 組件中通過 this.$store.commit(參數(shù)) 調(diào)用
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')
}
}
})
8忘朝、vue-cookies:操作cookie
npm install vue-cookies
npm install vue-cookies
Cookie.get('username')
Cookie.set('username', data.username, '20min')
Cookie.remove('username')
src/store/store.js
import Vue from 'vue'
import Vuex from 'vuex'
import Cookie from 'vue-cookies' # vue-cookies
Vue.use(Vuex)
export default new Vuex.Store({
// 組件中通過 this.$store.state.username 調(diào)用
state: {
username: Cookie.get('username'), # vue-cookies
token: Cookie.get('token') # vue-cookies
},
mutations: {
// 組件中通過 this.$store.commit(參數(shù)) 調(diào)用
saveToken: function (state, data) {
state.username = data.username
state.token = data.token
Cookie.set('username', data.username, '20min') # vue-cookies
Cookie.set('token', data.token, '20min')
},
clearToken: function (state) {
state.username = null
state.token = null
Cookie.remove('username') # vue-cookies
Cookie.remove('token')
}
}
})
三、代碼實(shí)現(xiàn)
前端代碼
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="stylesheet" href="./static/bootstrap-3.3.7-dist/css/bootstrap.css">
<script src="./static/bootstrap-3.3.7-dist/js/bootstrap.js"></script>
<title>s6vue</title>
</head>
<body>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
index.html
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 store from './store/store' //
import axios from 'axios' // 要是用axios判帮,就得先導(dǎo)入
Vue.prototype.$axios = axios //注冊(cè)局嘁,以后就可以用$axios來定義了
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
store,
router,
components: { App },
template: '<App/>'
})
app.vue
<template>
<div id="app">
<!--首頁(yè)里面永遠(yuǎn)是固定的東西-->
<ul class="nav nav-tabs">
<li><router-link to="/index">首頁(yè)</router-link> <!--用于點(diǎn)擊查看組件--></li>
<li><router-link to="/micro">學(xué)位課</router-link> <!--用于點(diǎn)擊查看組件--></li>
<li><router-link to="/course">課程</router-link></li> <!--用于點(diǎn)擊查看組件-->
<li><router-link to="/news">深科技</router-link></li> <!--用于點(diǎn)擊查看組件-->
<!--如果已經(jīng)登錄了,就不用在登錄了晦墙,在頁(yè)面還是顯示當(dāng)前用戶和注銷悦昵,如果沒有登錄就顯示登錄-->
<li v-if="this.$store.state.username">
<span><a>歡迎{{ this.$store.state.username }}登錄</a></span>
<span><a @click="logout()">注銷</a></span>
</li>
<li v-else=""> <router-link to="/login">登錄</router-link></li>
</ul>
<router-view/> <!--組件顯示的位置-->
</div>
</template>
<script>
export default {
name: 'App',
methods:{
logout(){
this.$store.state.username=''
this.$store.state.token=''
}
}
}
</script>
<style>
</style>
app.vue
router -- index.js
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'
})
router ---index.js
組件components
Index.vue
<template>
<div class="hello">
<h1>{{ msg }}</h1>
</div>
</template>
<script>
export default {
name: 'index',
data () {
return {
msg:"這里是首頁(yè)"
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>
</style>
Index.vue
Login.vue
<template>
<div class="">
<h2>登錄頁(yè)面</h2>
<p>用戶名:<input type="text" placeholder="username" v-model="username"></p>
<p>密碼:<input type="text" placeholder="password" v-model="password"></p>
<button><a @click="DoLogin()">提交</a></button>
</div>
</template>
<script>
export default {
name: 'index',
data () {
return {
username: "",
password: ""
}
},
methods:{
DoLogin (){
var that = this
// console.log(this.$axios);
this.$axios.request({ //發(fā)送axios請(qǐng)求
url:'http://127.0.0.1:8082/login/', //請(qǐng)求路徑
method:"POST",//請(qǐng)求方式
data:{ //要發(fā)送 的數(shù)據(jù)
username:this.username,
password:this.password
},
responseType:'json' //期望返回的類型是json的格式
}).then(function (response) { //吧返回的結(jié)果交給回調(diào)函數(shù)處理
//登錄成功之后,找到全局變量偎痛,吧用戶名和token賦值到其中
that.$store.commit('saveToken',response.data);
//重定向(登錄成功之后讓跳轉(zhuǎn)到index頁(yè)面)
that.$router.push('/index')
//為什么不直接用this呢旱捧?這里的this代表的是$axios,用that他代指的是整個(gè)Vue對(duì)象
})
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>
</style>
Login.vue
course.vue
<template>
<div class="">
<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: 'index',
data () {
return {
msg:'課程頁(yè)面',
courseList:[]
}
},
mounted:function () {
//當(dāng)組件一加載的時(shí)候就應(yīng)該去數(shù)據(jù)庫(kù)去獲取數(shù)據(jù)
this.initCourses()
},
methods:{
initCourses:function () {
var that = this
this.$axios.request({
url:'http://127.0.0.1:8082/course/',
method:"GET"
}).then(function (response) {
console.log(response);
that.courseList = response.data.courseList //吧從數(shù)據(jù)庫(kù)取的數(shù)據(jù)賦值到courseList列表里面
})
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>
</style>
course.vue
CourseDetail.vue
<template>
<div class="hello">
<div>課程詳細(xì)</div>
<h3>{{ title }}</h3>
<h3>{{ summary }}</h3>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data () {
return {
title:'',
summary:''
}
},
mounted:function () {
//當(dāng)組件一加載就執(zhí)行的函數(shù)
this.initCoursesDetail()
},
methods:{
initCoursesDetail(){
var nid = this.$route.params.id //獲取id
var that = this
var url = 'http://127.0.0.1:8082/course/' + nid + '.json'
this.$axios.request({
url:url,
methods:'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>
CoursesDetail
Micro.vue
<template>
<div class="hello">
<h2>歡迎報(bào)名學(xué)位課</h2>
</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>
Micro.vue
News.vue
<template>
<div class="hello">
<h2>深科技</h2>
</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>
News.vue
NotFound.vue
<template>
<div class="hello">
<h1>找不到頁(yè)面</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>
NotFound
保存全局使用的變量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 調(diào)用
state:{
username:Cookie.get('username'),
token:Cookie.get('token')
},
mutations:{
//組件中通過this.$store.commit(參數(shù))調(diào)用
saveToken:function (state,data) { //存放用戶名和token的函數(shù)
state.username = data.username //data代指從后端返回過來的數(shù)據(jù)
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')
}
}
})
store.js
后臺(tái)代碼
urls.py
"""day145vue和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 api 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<pk>\d+)\.(?P<format>[a-z-9]+)$', views.CourseView.as_view()),
]
urls.py
views.py
from 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':'在知識(shí)的海洋里一路向前'
}
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':'haiyn',
'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': "標(biāo)題標(biāo)題標(biāo)題",
'summary': '老師,太餓了踩麦。怎么還不下課'
}
else:
ret = {
'code':1000,
'courseList':[
{'name':'人生苦短枚赡,來學(xué)Python','id':1},
{'name':'32天學(xué)會(huì)java,歡迎報(bào)名','id':2},
{'name':'人工智能即將統(tǒng)領(lǐng)世界...','id':3},
]
}
response= JsonResponse(ret)
response['Access-Control-Allow-Origin'] = '*'
return response
views.py