Vue2:路由守卫
全局前置守卫beforeEach
beforeEach.((to,from,next)=>{})
全局后置守卫afterEach
afterEach.((to,from)=>{})
全局解析钩子beforeResolve
路由独享守卫beforeEnter
beforeEnter.((to,from,next)=>{})
组件内导航钩子
1
beforeRouteEnter
beforeRouteEnter.((to,from,next)=>{})
2
beforeRouteUpdate
beforeRouteUpdate.((to,from,next)=>{})
3
beforeRouteLeave
beforeRouteLeave.((to,from,next)=>{})
1、全局守卫
全局前置钩子router.beforeEach(fn),导航被触发----一般登录验证
//全局前置守卫 router.beforeEach((to, from, next) => { //用户未登录只能访问首页、登录注册页面 if (to.path == "/" || to.path == "/login" || to.path == "/register") { next(); } else { //去其他页面判断是否登录 let flag = window.localStorage.getItem("email"); //登录过直接放行 if (flag) { next() } else { //未登录则跳转到首页 Message({ message: '您尚未登录哦,请先登录!', type: 'warning', duration: 1500 }); next("/"); } } })
全局解析钩子router.beforeResolve(fn),组件初始化
//全局后置守卫 router.afterEach((to, from) => { window.scrollTo(0,0) })
所有路由匹配都会经过这三个钩子:beforeEach beforeResolve afterEach
2、路由独享的守卫
路由独享的守卫beforeEnter(to,from,next),路由初始化(组件未初始化)----
1)路由鉴权-----用户体验:界面,功能,bug,效率,权限
2)组件异步加载情景中(插件配置:syntax-dynamic-import)
routes:[{ path:"/test", component:()=>import("../components/Test.vue"), beforeEnter(to,from,next){ if(to.path==="/test"){ alert("请登录"); next(false); // 禁止跳转 }else{ next() } } }]
3)组件内部生命周期守卫
beforeRouteLeave 从该组件离开
beforeRouteEnter(to,from,next),组件被激活,使用不了this,故构造指定该next 可以接收一个回调函数接收当前vm 实例----路由传参获取参数,得到初始化数据
beforeRouteUpdate(to,from,next),组件重用时被调用----路由传参获取参数,避免增添watch 开销
导航守卫执行顺序
beforeRouteLeave < beforeEach < beforeRouteUpdate < beforeEnter < beforeRouteEnter < beforeResolve < afterEach
出发路由,预备从当前组件离开,判断路由变化,判断组件是否重用,判断新路由初始化,判断组件初始化,路由与组件初始化完毕,路由组件重定向完毕