闽公网安备 35020302035485号
注意: 必须要确保 next函数 在任何给定的导航守卫中都被调用过一次。它可以出现多次,但是只能在所有的逻辑路径都不重叠的情况下,否则会报错。
案例:
router.beforeEach((to, from, next) => {
if (to.name !== 'Login' && !isAuthenticated) next({ name: 'Login' })
else next()
})
一、全局路由守卫1.使用方式:
main.js中配置,在路由跳转前触发,这个钩子作用主要是用于登录验证,也就是路由还没跳转提前告知,以免跳转了再通知就为时已晚
2.代码:router.beforeEach((to,from,next)=>{})
3.例子:做登录判断router.beforeEach((to,from,next)=>{
if(to.path == '/login' || to.path == '/register'){
next();
}else{
alert('您还没有登录,系统将转到登录页https://www.duidaima.com/account/Login');
next('/login');
}
})
全局后置守卫1.使用方式:
main.js中配置,和beforeEach相反,它是在路由跳转完成后触发,它发生在beforeEach和beforeResolve之后,beforeRouteEnter(组件内守卫)之前。钩子不会接受next函数也不会改变导航本身
2.代码:router.afterEach((to,from)=>{})
全局解析守卫
1.使用方式:
main.js中配置,这个钩子和beforeEach类似,也是路由跳转前触发,区别是在导航被确认之前,同时在所有组件内守卫和异步路由组件被解析之后,即在 beforeEach 和 组件内beforeRouteEnter 之后,afterEach之前调用。
2.代码:router.beforeResolve((to,from,next)=>{})
一、组件内守卫beforeRouteEnter(to, from, next)
1.使用方式:
在组件模板中使用,跟methods: {}等同级别书写,组件路由守卫是写在每个单独的vue文件里面的路由守卫
2.代码:beforeRouteEnter(to, from, next) {
// 在组件生命周期beforeCreate阶段触发
console.log('组件内路由前置守卫 beforeRouteEnter', this) // 访问不到this
next((vm) => {
console.log('组件内路由前置守卫 vm', vm) // vm 就是this
})
},
beforeRouteUpdate(to, from, next)
1.使用方式:在组件模板中使用,跟methods: {}等同级别书写,组件路由守卫是写在每个单独的vue文件里面的路由守卫beforeRouteUpdate (to, from, next) {
// 同一页面,刷新不同数据时调用,
// 可以访问组件实例
}
beforeRouteLeave(to, from, next)
1.使用方式:在组件模板中使用,跟methods: {}等同级别书写,组件路由守卫是写在每个单独的vue文件里面的路由守卫beforeRouteLeave (to, from, next) {
// 导航离开该组件的对应路由时调用
// 可以访问组件实例
}
const router = new VueRouter({
routes: [
{
path: '/foo',
component: Foo,
beforeEnter: (to, from, next) => {
// ...
}
}
]
})
导航解析流程