全局前置__路由守卫
介绍:
在跳转前调用检验对路由进行权限控制
示例:
把路由改为以下格式:
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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具