vue这么实现路由过滤
路由过滤的实现方法
在Vue中实现路由过滤通常涉及导航守卫(Navigation Guards)的使用,以下是几种常见方式:
使用全局前置守卫
全局前置守卫router.beforeEach可以拦截所有路由跳转,适合实现权限过滤:
const router = new VueRouter({ ... })
router.beforeEach((to, from, next) => {
const isAuthenticated = checkAuth() // 自定义认证逻辑
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login')
} else {
next()
}
})
路由独享守卫
在路由配置中直接定义beforeEnter守卫,只对特定路由生效:
const routes = [
{
path: '/admin',
component: AdminPanel,
beforeEnter: (to, from, next) => {
if (!isAdmin()) next('/forbidden')
else next()
}
}
]
组件内守卫
在组件内部使用beforeRouteEnter、beforeRouteUpdate等守卫:
export default {
beforeRouteEnter(to, from, next) {
// 不能访问组件实例,因为守卫执行前组件未创建
getData().then(data => {
if (!data.valid) next(false) // 中止导航
else next(vm => vm.setData(data))
})
}
}
动态路由过滤
结合路由元信息和动态路由添加/删除实现过滤:
// 过滤路由表
function filterRoutes(routes, userRole) {
return routes.filter(route => {
if (route.meta && route.meta.roles) {
return route.meta.roles.includes(userRole)
}
return true
})
}
// 动态添加路由
router.addRoutes(filterRoutes(asyncRoutes, currentUser.role))
权限控制实践方案
基于角色的访问控制
在路由元信息中定义所需角色:
{
path: '/dashboard',
component: Dashboard,
meta: { roles: ['admin', 'editor'] }
}
路由白名单
设置无需认证的路由列表:
const whiteList = ['/login', '/register']
router.beforeEach((to, from, next) => {
if (whiteList.includes(to.path)) return next()
// ...其他验证逻辑
})
异步权限验证
结合后端API进行动态权限验证:
router.beforeEach(async (to, from, next) => {
try {
const { permissions } = await fetchUserPermissions()
if (to.meta.permission && !permissions.includes(to.meta.permission)) {
next('/403')
} else {
next()
}
} catch (error) {
next('/error')
}
})
错误处理与重定向
处理未授权访问
router.beforeEach((to, from, next) => {
if (!hasPermission(to)) {
next({ path: '/unauthorized', query: { from: to.fullPath } })
} else {
next()
}
})
取消导航
通过next(false)中止当前导航:
router.beforeEach((to, from, next) => {
if (isFormDirty() && !confirm('离开未保存的更改?')) {
next(false)
} else {
next()
}
})
以上方法可以根据实际项目需求组合使用,实现灵活的路由过滤机制。







