vue实现路由守卫
Vue 路由守卫的实现方法
Vue Router 提供了多种路由守卫,可以在路由导航过程中进行控制。以下是常见的几种实现方式:
全局前置守卫
使用 router.beforeEach 可以注册全局前置守卫,在路由跳转前执行:

router.beforeEach((to, from, next) => {
// 检查用户是否登录
if (to.meta.requiresAuth && !isAuthenticated()) {
next('/login')
} else {
next()
}
})
路由独享守卫
在路由配置中直接定义 beforeEnter 守卫:
const routes = [
{
path: '/admin',
component: AdminPanel,
beforeEnter: (to, from, next) => {
if (!isAdmin()) {
next('/access-denied')
} else {
next()
}
}
}
]
组件内守卫 在组件内部可以使用以下守卫:

export default {
beforeRouteEnter(to, from, next) {
// 在渲染该组件的对应路由被验证前调用
next(vm => {
// 通过 `vm` 访问组件实例
})
},
beforeRouteUpdate(to, from, next) {
// 当前路由改变但组件被复用时调用
next()
},
beforeRouteLeave(to, from, next) {
// 导航离开该组件的对应路由时调用
if (unsavedChanges()) {
if (confirm('有未保存的更改,确定离开吗?')) {
next()
} else {
next(false)
}
} else {
next()
}
}
}
全局解析守卫
使用 router.beforeResolve 注册全局守卫,在导航被确认前,所有组件内守卫和异步路由组件被解析后调用:
router.beforeResolve(async to => {
if (to.meta.requiresFetch) {
await fetchData()
}
})
全局后置钩子
使用 router.afterEach 注册全局后置钩子,不会改变导航本身:
router.afterEach((to, from) => {
sendToAnalytics(to.fullPath)
})
路由守卫执行顺序
- 导航被触发
- 调用失活组件的
beforeRouteLeave - 调用全局的
beforeEach - 在重用的组件里调用
beforeRouteUpdate - 在路由配置里调用
beforeEnter - 解析异步路由组件
- 在被激活的组件里调用
beforeRouteEnter - 调用全局的
beforeResolve - 导航被确认
- 调用全局的
afterEach - 触发 DOM 更新
- 调用
beforeRouteEnter中传给next的回调函数,创建好的组件实例会作为回调函数的参数传入
注意事项
- 确保总是调用
next()方法,否则钩子不会被解析 - 在
beforeRouteEnter中无法访问this,因为组件实例还未创建 - 路由守卫可以返回 Promise 来实现异步控制
- 使用
next(false)可以中断当前导航 - 使用
next('/path')或next({ path: '/' })可以跳转到不同位置






