全局前置__路由守卫
介绍:
在跳转前调用检验对路由进行权限控制
示例:
把路由改为以下格式:
import Vue from "vue"; import Router from "vue-router"; import Home from "./views/Home.vue"; import aboutone from './views/Aboutone'; import abouttow from './views/Abouttow'; import aboutoneson from './views/Aboutoneson'; Vue.use(Router); const router = Router({ routes: [{ // 页面开始就显示的路由 path: "/", name: "home", component: Home, }, { path: "/about", name: "about", component: () => import("./views/About.vue"), children: [{ path: 'aboutone', component: aboutone, children:[ { path: 'aboutoneson', component: aboutoneson, } ] }, { path: 'abouttow', component: abouttow, }, ] } ] });
//在每一次;写成箭头函数的写法时这时发现页面跳转不了了 router.beforeEach(()=>{
console.log('!!!');
})
//暴露router变量 export default router
beforeEach:指定一次路由每次切换时所调的函数
在每一次路由跳转之前进行调用,初始化时调用一次
beforeEach的三个参数:
第一个参数是:即将跳转的路由
第二个参数是:当前导航要离开的路由
第三个参数是:可以通行的路由
//beforeEach有三个参数 to,from,next router.beforeEach((to,from,next)=>{ console.log('!!!'); })
成功跳转
router.beforeEach((to,from,next)=>{ console.log(to,from); //判断如果要进入路由名字为'xiaoxi'或名字为'abtow', if (to.name==='xiaoxi' || to.name === 'abtow') { // 如果本地存储的Nuber值为yang就跳转,反之弹出权限不够 if (localStorage.getItem('Nuber') === 'yang') { next() } else{ alert('权限不够') } } else{ next() } })
失败跳转
我把获取的值的名字故意改成了yengrouter.beforeEach((to,from,next)=>{ console.log(to,from); //判断如果要进入路由名字为'xiaoxi'或名字为'abtow', if (to.name==='xiaoxi' || to.name === 'abtow') { // 如果本地存储的Nuber值为yang就跳转,反之弹出权限不够 if (localStorage.getItem('Nuber') === 'yeng') { next() } else{ alert('权限不够') } } else{ next() } })
方式二:
meta:{isAuth:true}谁需要校验就写在谁那
效果一样
import Vue from "vue"; import Router from "vue-router"; import Home from "./views/Home.vue"; import aboutone from './views/Aboutone'; import abouttow from './views/Abouttow'; import aboutoneson from './views/Aboutoneson'; Vue.use(Router); const router =new Router({ routes: [{ // 页面开始就显示的路由 path: "/", name: "home", component: Home, }, { path: "/about", name: "about", component: () => import("./views/About.vue"), children: [{ name:'xiaoxi', path: 'aboutone', component: aboutone, // 需要校验就写 meta:{isAuth:true}, children:[ { path: 'aboutoneson', component: aboutoneson, } ] }, { name:'abtow', path: 'abouttow', component: abouttow, meta:{isAuth:true}, }, ] } ] }); // 方式二 router.beforeEach((to,from,next)=>{ console.log(to,from); //判断如果在路由上meta.isAuth为true'为true就开始校验, if (to.meta.isAuth){ // 如果本地存储的Nuber值为yang就跳转,反之弹出权限不够 if (localStorage.getItem('Nuber') === 'yang') { next() } else{ alert('权限不够') } }else{ next() } }) export default router