全局后置__路由守卫
简介:
在初始化后被调用,跳转路由之后被调用
实现效果:
跳转到哪个路由哪个路由页的tilte改变文本
实例:
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, meta:{isAuth:false,title:'主页'}, }, { path: "/about", name: "about", component: () => import("./views/About.vue"), meta:{isAuth:false,title:'关于'}, children: [{ name:'xiaoxi', path: 'aboutone', component: aboutone, // 需要校验就写 meta:{isAuth:true,title:'列表一'}, children:[ { path: 'aboutoneson', component: aboutoneson, meta:{isAuth:true,title:'详情'}, } ] }, { name:'abtow', path: 'abouttow', component: abouttow, meta:{isAuth:true,title:'列表二'}, }, ] } ] }); // 前置路由守卫 router.beforeEach((to,from,next)=>{ console.log('前置',to,from); //判断如果在路由上meta.isAuth为true'为true就开始校验, if (to.meta.isAuth){ document.title = to.meta.title || '路由练习' // 如果本地存储的Nuber值为yang就跳转,反之弹出权限不够 if (localStorage.getItem('Nuber') === 'ycng') { //故意改的值 next() } else{ alert('权限不够') } } else{ document.title = to.meta.title || '路由练习' next() } }) // 后置路由守卫 初始化后被调用,跳转路由后被调用 // 后置守卫没有next参数 router.afterEach((to,from)=>{ console.log('后置',to,from); }) export default router
这时出现了一个bug当点击权限不够后tilte还是改变了路由没有跳转
解决:
只需要把前置那里的 document.title = to.meta.title || '路由练习' 添加到后置路由守卫就解决了// 前置路由守卫 router.beforeEach((to,from,next)=>{ console.log('前置',to,from); //判断如果在路由上meta.isAuth为true'为true就开始校验, if (to.meta.isAuth){ // 如果本地存储的Nuber值为yang就跳转,反之弹出权限不够 if (localStorage.getItem('Nuber') === 'yng') { next() } else{ alert('权限不够') } } else{ next() } }) // 后置路由守卫 初始化后被调用,跳转路由后被调用 // 后置守卫没有next参数 router.afterEach((to,from)=>{ console.log('后置',to,from); document.title = to.meta.title || '路由练习' }) 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工具