VUE从零开始系列(路由钩子及插件开发),呆萌小白上手VUE
第五章 路由鉤子及插件開發
前言
本章開始有點深入了哦~請同學們拿出你們的小本本,認真記筆記!上一章我們的登錄頁大概邏輯已經理順了,今天我們完善一下。
登錄標識(token)
有加群的小伙伴提出登錄沒有token,因為我們是自己mock數據的,所以只能寫死返回一個冒牌token~,請打開src/mock/index.js,把它改造一下,在返回結果中,新增token字段:
//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
//設置cookie const setCookie = (c_key,c_val,exdays) => {let exdate=new Date();exdate.setTime(exdate.getTime() + 24*60*60*1000*exdays);//保存的天數//字符串拼接cookiewindow.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
//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里注冊一下。
// 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 = falseVue.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中:
<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:
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:每個鉤子方法接收三個參數:
- to:即將要進入的目標
- from : 當前導航正要離開的路由
- next(): 進行管道中的下一個鉤子。一定要調用該方法來 resolve 這個鉤子。next({ path: '/login' })這個寫法就是把當前路由重定向到我們指定的路由。
這里要強調一下,為什么不直接用this.$Cookies來調用我們的插件呢,因為當鉤子執行前,組件實例還沒被創建,this自然也就是個野指針嘍。所以我們只能把插件引入再調用。
結語
繼續廣告下我們的Q群:57991865,歡迎進群交流。
完整代碼點我,密碼:czkn
所有章節
- 第一章 安裝腳手架
- 第二章 初體驗
- 第三章 登錄頁
- 第四章 axios
總結
以上是生活随笔為你收集整理的VUE从零开始系列(路由钩子及插件开发),呆萌小白上手VUE的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Docker 网络之进阶篇
- 下一篇: 如何编写一个npm包,可以公共使用?