在路由.js文件中全局守卫router.beforeEach添加
router.beforeEach((to, from, next) => {
let access = [
//当前权限列表
]
if (canTurnTo(to.name, access, routes)){//routes当前路由列表
console.log("当前有权限")
next() // 有权限,可访问
}else{
console.log("当前无权限")
next()
}// 无权限,重定向到401页面
})
const canTurnTo = (path, access, routes) => {
const routePermissionJudge = (list) => {
return list.some(item => {
if (item.children && item.children.length) {
return routePermissionJudge(item.children)
} else if (item.name === path) {
return hasAccess(access, item)
}
})
}
return routePermissionJudge(routes)
}
const hasAccess = (access, route) => {
if (route.meta && route.meta.access) return hasOneOf(access, route.meta.access)
else return true
}
const hasOneOf = (targetarr, arr) => {
return targetarr.some((_) => arr.indexOf(_) > -1);
};
//持续更新中
本文介绍了如何在Vue Router的beforeEach守卫中实现全局权限检查,通过canTurnTo函数判断用户是否有访问特定路由的权限,确保了应用的安全访问控制。
347

被折叠的 条评论
为什么被折叠?



