vue实现路由拦截
路由拦截的实现方式
在Vue中实现路由拦截通常使用Vue Router的导航守卫功能。导航守卫允许在路由跳转前、跳转后或跳转过程中执行自定义逻辑,常用于权限控制、登录验证等场景。
全局前置守卫
通过router.beforeEach注册全局前置守卫,每次路由跳转前都会触发。以下是一个检查用户是否登录的示例:
const router = new VueRouter({ ... })
router.beforeEach((to, from, next) => {
const isAuthenticated = localStorage.getItem('token')
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login')
} else {
next()
}
})
路由独享守卫
在路由配置中直接定义beforeEnter守卫,只对特定路由生效:
const router = new VueRouter({
routes: [
{
path: '/admin',
component: Admin,
beforeEnter: (to, from, next) => {
if (user.role !== 'admin') next('/403')
else next()
}
}
]
})
组件内守卫
在组件内部使用导航守卫,包括beforeRouteEnter、beforeRouteUpdate和beforeRouteLeave:
export default {
beforeRouteEnter(to, from, next) {
// 不能访问组件实例
next(vm => {
// 通过vm访问组件实例
})
},
beforeRouteLeave(to, from, next) {
const answer = confirm('确定要离开吗?')
if (answer) next()
else next(false)
}
}
元字段权限控制
结合路由的meta字段实现更细粒度的权限控制:
const routes = [
{
path: '/dashboard',
component: Dashboard,
meta: { requiresAuth: true, roles: ['admin', 'editor'] }
}
]
router.beforeEach((to, from, next) => {
const userRole = getUserRole()
if (to.meta.roles && !to.meta.roles.includes(userRole)) {
next('/403')
} else {
next()
}
})
动态路由处理
对于动态加载的路由,可以在路由加载完成后添加全局守卫:
function loadRoutes() {
return fetchRoutes().then(routes => {
router.addRoutes(routes)
router.beforeEach((to, from, next) => {
// 守卫逻辑
})
})
}
错误处理
捕获并处理导航过程中的错误:
router.onError(error => {
console.error('路由错误:', error)
if (error.name === 'NavigationDuplicated') {
// 处理重复导航错误
}
})
以上方法可以根据实际需求组合使用,构建完整的路由拦截系统。注意避免在守卫中出现无限循环的导航跳转。







