Vue Router 有哪几种路由守卫?
Vue Router 中有 三种主要的路由守卫(导航守卫),用于在路由跳转过程中进行拦截、校验或执行逻辑。
一、全局守卫(Global Guards)
1. beforeEach
在每次导航前触发。
可用于权限验证、登录状态检查等。
router.beforeEach((to, from, next) => {
console.log('全局前置守卫')
next() // 必须调用 next() 才能继续导航
})
2. beforeResolve
所有组件内守卫解析完后触发。
很少用,但可以处理一些更靠后的逻辑。
router.beforeResolve((to, from, next) => {
console.log('全局解析守卫')
next()
})
3. afterEach
导航完成后触发(没有 next,不能中断导航)。
可用于页面打点、设置标题、关闭 loading 等。
router.afterEach((to, from) => {
console.log('全局后置守卫')
})
二、路由独享守卫(Per-Route Guard)
在定义路由时写在 meta 外的配置项中。
{
path: '/admin',
component: Admin,
beforeEnter: (to, from, next) => {
console.log('路由独享守卫')
next()
}
}
三、组件内守卫(In-Component Guards)
只能在使用 Vue Component 的路由中触发(即被 <router-view> 渲染)。
1. beforeRouteEnter(to, from, next)
路由进入前调用。
注意:this 还未被创建,不能访问 this!
如果需要访问组件实例,可以使用 next(vm => {})
beforeRouteEnter(to, from, next) {
next(vm => {
console.log('组件内 beforeRouteEnter', vm)
})
}
2. beforeRouteUpdate(to, from, next)
在当前组件复用时(参数变了)调用。
beforeRouteUpdate(to, from, next) {
console.log('组件内 beforeRouteUpdate')
next()
}
3. beforeRouteLeave(to, from, next)
离开当前组件前触发。
常用于提示保存、拦截离开等。
beforeRouteLeave(to, from, next) {
const answer = window.confirm('确定要离开吗?未保存的内容将丢失!')
if (answer) next()
else next(false)
}
总结对比表:
| 守卫类型 | 位置 | 触发时机 | 是否可以阻止导航 |
|---|---|---|---|
beforeEach |
全局 | 每次导航前 | ✅ |
beforeResolve |
全局 | 所有组件守卫后 | ✅ |
afterEach |
全局 | 每次导航完成后 | ❌(不能阻止) |
beforeEnter |
路由独享 | 进入该路由前 | ✅ |
beforeRouteEnter |
组件内 | 路由进入组件前 | ✅(无 this) |
beforeRouteUpdate |
组件内 | 复用组件时 | ✅ |
beforeRouteLeave |
组件内 | 离开组件前 | ✅ |
浙公网安备 33010602011771号