vue路由拦截怎么实现
Vue路由拦截的实现方法
在Vue中,可以通过路由守卫(Navigation Guards)来实现路由拦截,主要用于权限控制、登录验证等场景。
全局前置守卫
使用router.beforeEach注册全局前置守卫,在路由跳转前进行拦截:
const router = new VueRouter({ ... })
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
if (!auth.loggedIn()) {
next({
path: '/login',
query: { redirect: to.fullPath }
})
} else {
next()
}
} else {
next()
}
})
路由独享守卫
在路由配置中直接定义beforeEnter守卫:

const router = new VueRouter({
routes: [
{
path: '/dashboard',
component: Dashboard,
beforeEnter: (to, from, next) => {
if (!store.getters.isAuthenticated) {
next('/login')
} else {
next()
}
}
}
]
})
组件内守卫
在组件内部使用beforeRouteEnter、beforeRouteUpdate和beforeRouteLeave:
export default {
beforeRouteEnter(to, from, next) {
// 不能获取组件实例`this`
next(vm => {
// 通过`vm`访问组件实例
})
},
beforeRouteUpdate(to, from, next) {
// 当前路由改变但组件被复用时调用
next()
},
beforeRouteLeave(to, from, next) {
// 导航离开该组件时调用
if (confirm('确定要离开吗?')) {
next()
} else {
next(false)
}
}
}
全局解析守卫
使用router.beforeResolve注册全局守卫,在导航被确认前调用:

router.beforeResolve((to, from, next) => {
// 适合获取数据或执行其他异步操作
next()
})
全局后置钩子
使用router.afterEach注册全局后置钩子,不会改变导航本身:
router.afterEach((to, from) => {
// 适合分析、更改页面标题等操作
document.title = to.meta.title || '默认标题'
})
路由元信息
配合路由元信息meta可以更灵活地控制权限:
const router = new VueRouter({
routes: [
{
path: '/admin',
component: Admin,
meta: { requiresAuth: true, roles: ['admin'] }
}
]
})
动态添加路由
通过router.addRoutes动态添加路由实现权限过滤:
// 过滤有权限的路由
const accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
router.addRoutes(accessedRoutes)
以上方法可以单独使用或组合使用,根据项目需求选择最合适的实现方式。路由守卫的执行顺序为:全局前置守卫→路由独享守卫→组件内守卫→全局解析守卫→全局后置钩子。






