存在一个角色权限数组,在给定的路由数组外面,找出有权限的项组成新路由,meta.roles 外面的任意一个角色存在于角色列表外面,就有权限,如果父路由没有权限,子路由不应该权限
场景:
存在路由如:
route = [
{
path: '/home',
meta: {roles: [2, 9]
},
children: [
{
meta: {roles: [2]
}
},
{
meta: {roles: [9]
}
}
]
},
{
meta: {roles: [90, 4]
},
children: [
{
meta: {roles: [4]
}
},
{
meta: {roles: [90]
}
}
]
},
{
path: '/home',
meta: {roles: [100, 1]
},
children: [
{
meta: {roles: [2]
}
}
]
}
]
以后用户领有的角色列表,如:rolesList = [2,9,90]
要依据角色列表输入最终有权限的路由,上述场景输入:
result = [
{
path: '/home',
meta: {roles: [2, 9]
},
children: [
{
meta: {roles: [2]
}
},
{
meta: {roles: [9]
}
}
]
},
{
path: '/home',
meta: {roles: [90, 4]
},
children: [
{
meta: {roles: [90]
}
}
]
}
]
实现办法 1:
// 以后路由是否有权限
function existJurisdiction(router) {if (!router.meta) return false
let {roles} = router.meta
return rolesList.some(item => roles.includes(item))
}
// 找出有权限的一级路由
function getResult (route) {
let _result = route.filter(item => {let _existJurisdiction = existJurisdiction(item)
// 以后路由有权限,则找出子路由中存在权限的路由赋值给子路由
_existJurisdiction && (item.children = (item.children && getResult(item.children)))
return _existJurisdiction
})
return _result
}
let result = getResult(route)
实现 2:(思路和实现 1 一样,existJurisdiction 函数的判断逻辑改为以后 roles 和角色权限列表是否有交加,有则示意有权限)
function existJurisdiction(router) {if (!router.meta) return false
let {roles} = router.meta
// return (roles.length + rolesList.length) !== Array.from(new Set([...roles, ...rolesList])).length
return (roles.length + rolesList.length) !== (new Set([...roles, ...rolesList])).size
}