本章開始有點深刻了哦~請同窗們拿出大家的小本本,認真記筆記!上一章咱們的登陸頁大概邏輯已經理順了,今天咱們完善一下。css
有加羣的小夥伴提出登陸沒有token,由於咱們是本身mock數據的,因此只能寫死返回一個冒牌token~,請打開src/mock/index.js
,把它改造一下,在返回結果中,新增token字段:vue
//mock/index.js
import Mock from 'mockjs'
//驗證帳號密碼
let uTable = {
'password': '123456',
'username':"admin",
'token':'abcde12345'
}
const data = Mock.mock('http://user.com/login', (param) => {
let dataJson = JSON.parse(param.body)
if((dataJson.username == uTable.username) && (dataJson.password == uTable.password)) {
let result = {
state: 'ok',
token: uTable.token
}
return result
} else {
let result = {
state: 'no',
token: ''
}
return result
}
})
export default {
data
}
複製代碼
此時在登陸組件中,即可以打印出結果,若是帳號密碼匹配的話,你會看到多了token字段,接着咱們要把獲取的toke種到cookie裏,由於有不少地方要操做cookie,咱們寫成插件,方便調用。在src下,新建plugins/components/cookies/index.js
webpack
//設置cookie
const setCookie = (c_key,c_val,exdays) => {
let exdate=new Date();
exdate.setTime(exdate.getTime() + 24*60*60*1000*exdays);//保存的天數
//字符串拼接cookie
window.document.cookie=c_key+ "=" +c_val+";path=/;expires="+exdate.toGMTString();
}
//獲取cookie
const getCookie = (c_key) => {
let arr,reg=new RegExp("(^| )"+c_key+"=([^;]*)(;|$)");
if(arr=document.cookie.match(reg))
return unescape(arr[2]);
else
return null;
}
//刪除cookie
const delCookie = (c_key) => {
let exp = new Date();
exp.setTime(exp.getTime() - 1);
let cval=getCookie(name);
if(cval!=null)
document.cookie= name + "="+cval+";expires="+exp.toGMTString();
}
//對外暴露方法
export default {
setCookie,
getCookie,
delCookie
}
複製代碼
爲了避免必每次調用插件都得引入,咱們把它添加爲全局方法,新建plugins/index.js
ios
//plugins/index.js
//引入剛纔寫好的插件
import Cookies from './components/cookies';
export default {
install(Vue,options) {
Vue.prototype.$Cookies = Cookies
}
}
複製代碼
install
:當咱們在main.js中用Vue.use()的時候,會默認調用install方法,而且會返回兩個值:vue實例,可選的options參數。這一步完成後,咱們在main.js
裏註冊一下。web
// 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 ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import axios from 'axios'
import Mock from '@/mock/index'
//引入剛纔的plugins/index.js
import plugins from '@/plugins'
Vue.use(ElementUI);
//綁定到全局
Vue.use(plugins);
Vue.config.productionTip = false
Vue.prototype.$http= axios
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
複製代碼
插件搞定!而後就能夠在任意組件中,經過this.$Cookies.setCookie()
來進行調用。如今打開src/pages/user/Login.vue
組件,經過咱們封裝的cookie插件,把token種到cookie中:vue-router
<template>
<div class="login_page">
<section class="form_contianer">
<div class="manage_tip">
<p>第一個後臺管理系統</p>
</div>
<el-form>
<el-form-item prop="username">
<el-input placeholder="用戶名" v-model="uname"></el-input>
</el-form-item>
<el-form-item prop="password">
<el-input type="password" placeholder="密碼" v-model="pwd"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" class="submit_btn" @click="login">登錄</el-button>
</el-form-item>
</el-form>
</section>
</div>
</template>
<script>
export default {
data() {
return {
uname:'',
pwd:''
}
},
methods: {
login () {
let self = this
this.$http({
method: 'get',
url: 'http://user.com/login',
data: {
username: this.uname,
password: this.pwd
}
})
.then((r) => {
if(r.data.state == 'ok') {
self.$Cookies.setCookie('mytoken',r.data.token)
self.$router.push({path:'/'})
} else {
self.$message.error('帳號或密碼錯誤,請從新填寫');
}
})
}
}
}
</script>
<style scoped>
@import '../../assets/css/login.css';
</style>
複製代碼
cookie種好了,童鞋們能夠自行console一下看是否成功,至於怎麼打印,調用咱們封裝的插件嘍,若是不會請自行領悟。。種了cookie還沒完,咱們還須要在路由跳轉前進行判斷,若是沒有cookie,也就是沒登陸,那咱們就不容許打開首頁或其餘頁面,這裏就要用到路由鉤子beforeEnter
,如今打開src/router/index.js
:element-ui
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Login from '@/pages/user/Login'
import $Cookies from '@/plugins/components/cookies'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld,
//路由鉤子,在跳轉前進行判斷
beforeEnter: (to, from, next) => {
console.log($Cookies.getCookie('mytoken'))
if($Cookies.getCookie('mytoken')) {
next()
}else {
next({path:'/login'})
}
}
},
{
path: '/login',
name: 'Login',
component: Login
}
]
})
複製代碼
beforeEnter
:每一個鉤子方法接收三個參數:axios
這裏要強調一下,爲何不直接用this.$Cookies來調用咱們的插件呢,由於當鉤子執行前,組件實例還沒被建立,this天然也就是個野指針嘍。因此咱們只能把插件引入再調用。bash
繼續廣告下咱們的Q羣:57991865,歡迎進羣交流。cookie
完整代碼點我,密碼:czkn