GenerateRoutes 方法怎么正确地将 asyncRoutes 中的路由添加到 dynamicRoutes 中
时间: 2024-03-16 13:41:15 浏览: 18
在 Vue-element-admin 中,`asyncRoutes` 是所有可能出现的路由集合,而 `dynamicRoutes` 是根据用户角色动态生成的路由。`GenerateRoutes` 方法的作用是根据用户角色生成动态路由 `dynamicRoutes`,其中包含了用户有权限访问的路由,而这些路由最终会被用于生成菜单和路由。下面是 `GenerateRoutes` 方法示例代码:
```js
const state = {
routes: [], // 所有路由集合
addRoutes: [] // 用户有权限访问的路由集合
}
const mutations = {
SET_ROUTES: (state, routes) => {
state.addRoutes = routes
state.routes = constantRoutes.concat(routes)
}
}
const actions = {
generateRoutes({ commit }, roles) {
return new Promise(resolve => {
let accessedRoutes
if (roles.includes('admin')) {
accessedRoutes = asyncRoutes || []
} else {
accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
}
commit('SET_ROUTES', accessedRoutes)
resolve(accessedRoutes)
})
}
}
export default {
namespaced: true,
state,
mutations,
actions
}
```
在上面的代码中,`generateRoutes` 方法接收一个参数 `roles`,表示当前用户的角色列表。如果用户角色包含 `admin`,那么所有路由都是可访问的,直接将 `asyncRoutes` 中的所有路由添加到 `dynamicRoutes` 中即可。如果用户角色不是 `admin`,则需要根据用户角色筛选出所有有权限访问的路由。
在 `generateRoutes` 方法中,调用了 `filterAsyncRoutes` 方法,它会根据用户角色筛选出所有有权限访问的路由。以下是 `filterAsyncRoutes` 方法示例代码:
```js
/**
* Use meta.role to determine if the current user has permission
* @param roles
* @param route
*/
function hasPermission(roles, route) {
if (route.meta && route.meta.roles) {
return roles.some(role => route.meta.roles.includes(role))
} else {
return true
}
}
/**
* Filter asynchronous routing tables by recursion
* @param routes asyncRoutes
* @param roles
*/
export function filterAsyncRoutes(routes, roles) {
const res = []
routes.forEach(route => {
const tmp = { ...route }
if (hasPermission(roles, tmp)) {
if (tmp.children) {
tmp.children = filterAsyncRoutes(tmp.children, roles)
}
res.push(tmp)
}
})
return res
}
```
在上面的代码中,`filterAsyncRoutes` 方法会递归地遍历所有路由,检查每个路由的元信息中的 `roles` 属性是否包含在用户角色列表中。如果包含,则将该路由加入到结果集合中,并递归处理它的子路由。最终返回所有有权限访问的路由。
在 `generateRoutes` 方法中,根据用户角色调用 `filterAsyncRoutes` 方法筛选出所有有权限访问的路由,并将其添加到 `dynamicRoutes` 中,最终返回该集合。这样,在菜单和路由生成时,就可以根据 `dynamicRoutes` 中的路由动态生成菜单和路由了。