1. 程式人生 > >遞迴獲取對應的許可權的路由

遞迴獲取對應的許可權的路由

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <script
> // 判斷當前的使用者是否有該路由的許可權 /* routes.filter(route => route.meta.roles.includes(user.role)) roles 是使用者的許可權表 [] 可以有多種許可權 route就是對應的路由配置中的路由物件 roles: ['a', 'b'] route.meta.roles: ['c'] roles會被迴圈兩次, 第一次 role是 'a' 判斷a是否在route.meta.roles中 第二次 role是 'b' 判斷b是否在route.meta.roles中 最終some的結果為false roles: ['a'] route.meta.roles: ['a', 'b'] a roles: ['a'] route
*/ const routes = [ { path: '/a', meta: { roles: ['a', 'b'] } }, { path: '/b', children: [ { path: 'a', meta: { roles: ['a'] } }, { path: 'b', meta: { roles: [
'b'] } } ] } ] function hasPermission(roles, route) { if (route.meta && route.meta.roles) { return roles.some(role => route.meta.roles.indexOf(role) >= 0) } else { return true } } /** * 遞迴過濾非同步路由表,返回符合使用者角色許可權的路由表 * @param asyncRouterMap * @param roles */ /* asyncRouterMap 是一個路由配置陣列 [ { children: [ {} ] }, {}, {} ] */ function filterAsyncRouter(asyncRouterMap, roles) { const accessedRouters = asyncRouterMap.filter(route => { if (hasPermission(roles, route)) { if (route.children && route.children.length) { route.children = filterAsyncRouter(route.children, roles) } return true } return false }) return accessedRouters } console.log(filterAsyncRouter(routes, ['a'])) /* const routes = [ { path: '/', meta: { role: ['admin', 'a', 'b'] }, children: [ { path: 'a', meta: { role: ['admin', 'a'] } } ] }, { path: '/edit', meta: { role: ['admin', 'b'] } } ] */ /* admin / /a /edit a / /a b / /edit */ function filterRole (arr) { const newArr = arr.filter(route => { if (route.meta.role.includes('b')) { // 噹噹前路由有role屬性時,判斷當前路由是否有children子路由,如果有子路由,則繼續判斷子路由中是否有role if (route.children && route.children.length) { // 遞迴篩選有對應許可權的路由 route.children = filterRole(route.children) } return true } }) return newArr } // console.log(newArr) // const asyncRoutes = filterRole(routes) // 最終呼叫router.addRoutes(asyncRoutes) </script> </body> </html>