全局守卫分为全局前置守卫,全局解析守卫。全局后置钩子三个。
全局前置守卫
当一个导航触发时,全局前置守卫按照创建的顺序调用。守卫可以是异步解析执行,此时,导航在所有守卫执行完之前一直处于挂起状态。全局前置守卫使用router.beforeEach注册。代码如下:
const router = new VueRouter({...})
router.beforeEach((to, from, next) => {
//这里执行操作
//next调用
})
在使用全局前置守卫的时候,一定要确保next函数的正确调用。例如,下面就是一个错误的例子:
router.beforeEach((to, from, next) => {
if (!isAuthenticated) next('/login')
//如果用户没有通过验证,那么next函数就被调用了两次
next()
})
正确的做法是:
router.beforeEach((to, from, next) => {
if(!isAuthenticated) {
next('/login');
}else{
next();
}
})
全局解析守卫
全局解析守卫使用router.beforeResolve注册。它和全局前置守卫类似,区别在于,在导航被确认之前,在所有组件内守卫和异步路由组件被解析之后,全局解析守卫才被调用。
const router = new VueRouter({...})
router.beforeResolve((to, from, next) => {
//...
})
全局后置钩子
全局后置钩子使用router.afterEach注册,在导航确认之后调用。
const router = new VueRouter({...})
router.afterEach((to, from) => {
//...
})
与守卫不同的是,全局后置钩子不接受next函数,也不会改变导航。