vue实现路由守卫
Vue 路由守卫的实现方法
Vue Router 提供了多种路由守卫(Navigation Guards),用于在路由跳转前后执行特定逻辑,例如权限验证、页面跳转拦截等。以下是常见的路由守卫实现方式:
全局前置守卫(beforeEach)
在路由跳转前执行,常用于登录验证或权限控制:
router.beforeEach((to, from, next) => {
const isAuthenticated = checkAuth() // 自定义验证方法
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login')
} else {
next()
}
})
全局解析守卫(beforeResolve)
在导航被确认前触发,适合获取数据或执行异步操作:
router.beforeResolve(async (to, from, next) => {
try {
await fetchData() // 异步操作
next()
} catch (error) {
next('/error')
}
})
全局后置钩子(afterEach)
路由跳转完成后触发,适合页面统计或日志记录:
router.afterEach((to, from) => {
sendToAnalytics(to.fullPath) // 自定义统计方法
})
路由独享守卫(beforeEnter)
在单个路由配置中定义:
const routes = [
{
path: '/admin',
component: AdminPanel,
beforeEnter: (to, from, next) => {
if (!isAdmin()) next('/forbidden')
else next()
}
}
]
组件内守卫
在组件内部定义:
beforeRouteEnter:进入组件前调用beforeRouteUpdate:路由变化但组件复用时调用beforeRouteLeave:离开组件前调用
export default {
beforeRouteEnter(to, from, next) {
// 不能访问组件实例(this)
next(vm => {
// 通过vm访问组件实例
})
},
beforeRouteUpdate(to, from, next) {
// 可以访问this
this.userData = null
next()
},
beforeRouteLeave(to, from, next) {
if (this.hasUnsavedChanges) {
if (!confirm('确定离开?')) return next(false)
}
next()
}
}
路由守卫执行顺序
- 导航被触发
- 调用失活组件的
beforeRouteLeave - 调用全局的
beforeEach - 在重用的组件里调用
beforeRouteUpdate - 在路由配置里调用
beforeEnter - 解析异步路由组件
- 在被激活的组件里调用
beforeRouteEnter - 调用全局的
beforeResolve - 导航被确认
- 调用全局的
afterEach - 触发 DOM 更新
- 调用
beforeRouteEnter中传给next的回调函数
路由元信息(meta)
可通过 meta 字段传递自定义信息:

const routes = [
{
path: '/profile',
component: Profile,
meta: { requiresAuth: true }
}
]
在守卫中通过 to.meta 访问这些信息。






