Vue路由守卫(Navigation Guards)是Vue Router提供的一系列钩子函数,用于控制路由的导航行为。通过这些守卫,开发者可以在路由跳转之前或之后执行特定的逻辑,比如权限验证、数据预加载等。以下是Vue路由守卫的几种类型:
1. 全局前置守卫(Global Before Guards)
这是最常用的守卫类型,可以应用于所有路由。它在导航发生之前被调用,可以用来做全局性的权限检查或数据预加载。
router.beforeEach((to, from, next) => {
// to: 即将进入的目标路由对象
// from: 当前导航正要离开的路由
// next: 一个回调函数,用来通知Vue Router是否继续进行导航
if (to.matched.some(record => record.meta.requiresAuth)) {
if (!store.getters.isLoggedIn) {
next({
path: '/login',
query: { redirect: to.fullPath }
})
} else {
next()
}
} else {
next()
}
})
2. 全局解析守卫(Global Resolve Guards)
这个守卫在全局前置守卫之后,但在组件守卫和异步路由组件加载之前被调用。
router.beforeResolve((to, from, next) => {
// 类似于 beforeEach,但是允许访问组件实例 `this`
// 因为当守卫被调用时,组件实例已经被创建了
})
3. 全局后置钩子(Global After Hooks)
这些钩子在导航完成后被调用,不带有 next
函数,因此不能影响导航本身。
router.afterEach((to, from) => {
// ...
})
4. 路由独享守卫(Route-Exclusive Guards)
可以在路由配置中直接定义,只作用于该路由。
const routes = [
{
path: '/secret',
component: SecretComponent,
beforeEnter: (to, from, next) => {
// ...
}
}
]
5. 组件内的守卫(Component-Specific Guards)
这些守卫是定义在组件内的,用于控制该组件的进入和离开。
beforeRouteEnter
: 在当前路由开始进入之前调用,但是没有访问到this
组件实例。
export default {
beforeRouteEnter (to, from, next) {
// ...
}
}
beforeRouteUpdate
: 在当前路由改变,但是该组件被复用时调用。
export default {
beforeRouteUpdate (to, from, next) {
// ...
}
}
beforeRouteLeave
: 在当前路由即将离开时调用。
export default {
beforeRouteLeave (to, from, next) {
// ...
}
}
使用这些守卫,你可以根据应用的具体需求来控制路由的导航流程,实现更加复杂的业务逻辑。