權限校驗是指,當我們沒有登錄的時候,訪問需要登錄的頁面,是無法直接進入的,需要登錄后才會顯示跳轉內容。
在Vue官網中叫導航守衛,官方參考:https://router.vuejs.org/zh/guide/advanced/navigation-guards.html
正如其名,vue-router
提供的導航守衛主要用來通過跳轉或取消的方式守衛導航。有多種機會植入路由導航過程中:全局的, 單個路由獨享的, 或者組件級的。
通過 router.beforeEach來注冊全局守衛。
這里需要引用router目錄下的index.js里的VueRouter實例
# router/index.js文件
import Vue from "vue"; import VueRouter from "vue-router"; import login from "../views/Login" import home from "../components/Layout.vue" import homes from "../views/Home.vue" import dev from "../views/Dev.vue" Vue.use(VueRouter); // const originalPush = VueRouter.prototype.push // VueRouter.prototype.push = function push(location) { // return originalPush.call(this, location).catch(err => err) // }; export default new VueRouter({ routes:[ { path:"/",name:"/",component:login}, { path:"/home",name:"home", component:homes}, { path:"/tools",name:"tools",component:homes,children:[ {path:"/tools/dev",name:"dev",component:dev} ]} ] })
創建一個新的js文件,引入router
// 1、引入router,通過router實例實現頁面驗證token import Router from "../router/index.js" Router.beforeEach((to,from,next)=>{ // 使用beforEach-》to:目標路徑,from當前路徑,next是跳轉方法 const token = localStorage.getItem("token") // 這里我判斷token是否存在 if(token){ next() //存在就允許跳轉下一個路徑 }else{ if(to.path !=="/"){ //to.path 可以獲得跳轉的路徑 next({path:"/"}) //next里可以傳跳轉路徑 }else{ next() } } })