From 4c49259c9287c9d473b2c022e5af2372ce04fd1d Mon Sep 17 00:00:00 2001 From: inklake Date: Mon, 17 Sep 2018 17:46:20 +0800 Subject: [PATCH] refine[permission.js]: switch roles will refresh the sidebar correctly (#1067) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 后台菜单->权限测试页->指令权限 切换角色 会正确 刷新侧边栏 > /src/store/modules/permission.js 原方法在递归筛选侧边菜单后, 会意外修改原始 asyncRouterMap 导致侧边菜单重绘不正常 已经用新方法替代修复 结果入下图 ![图片](https://s1.ax1x.com/2018/09/07/iCL7f1.gif) --- src/store/modules/permission.js | 25 ++++++++++++++----------- src/store/modules/user.js | 3 ++- 2 files changed, 16 insertions(+), 12 deletions(-) diff --git a/src/store/modules/permission.js b/src/store/modules/permission.js index ce1aafa6..97de701e 100644 --- a/src/store/modules/permission.js +++ b/src/store/modules/permission.js @@ -7,7 +7,7 @@ import { asyncRouterMap, constantRouterMap } from '@/router' */ function hasPermission(roles, route) { if (route.meta && route.meta.roles) { - return roles.some(role => route.meta.roles.indexOf(role) >= 0) + return roles.some(role => route.meta.roles.includes(role)) } else { return true } @@ -15,20 +15,23 @@ function hasPermission(roles, route) { /** * 递归过滤异步路由表,返回符合用户角色权限的路由表 - * @param asyncRouterMap + * @param routes asyncRouterMap * @param roles */ -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) +function filterAsyncRouter(routes, roles) { + const res = [] + + routes.forEach(route => { + const tmp = { ...route } + if (hasPermission(roles, tmp)) { + if (tmp.children) { + tmp.children = filterAsyncRouter(tmp.children, roles) } - return true + res.push(tmp) } - return false }) - return accessedRouters + + return res } const permission = { @@ -47,7 +50,7 @@ const permission = { return new Promise(resolve => { const { roles } = data let accessedRouters - if (roles.indexOf('admin') >= 0) { + if (roles.includes('admin')) { accessedRouters = asyncRouterMap } else { accessedRouters = filterAsyncRouter(asyncRouterMap, roles) diff --git a/src/store/modules/user.js b/src/store/modules/user.js index 13e76399..0f7e2296 100644 --- a/src/store/modules/user.js +++ b/src/store/modules/user.js @@ -122,7 +122,7 @@ const user = { }, // 动态修改权限 - ChangeRoles({ commit }, role) { + ChangeRoles({ commit, dispatch }, role) { return new Promise(resolve => { commit('SET_TOKEN', role) setToken(role) @@ -132,6 +132,7 @@ const user = { commit('SET_NAME', data.name) commit('SET_AVATAR', data.avatar) commit('SET_INTRODUCTION', data.introduction) + dispatch('GenerateRoutes', data) // 动态修改权限后 重绘侧边菜单 resolve() }) })