vue - 路由权限控制
router 目录结构
| └── router |
| ├── modules |
| │ ├── administrator.js |
| │ ├── [identity].js |
| │ └── xxx.js |
| └── index.js |
身份路由导出
| |
| export { default as [identity] } from './modules/[identity]'; |
根据权限生成路由
| |
| import { [identity1], [identity2] } from '@/router' |
| |
| const Routes = { |
| identity1: [identity1], |
| identity2: [identity2] |
| } |
| |
| |
| |
| |
| |
| |
| function hasPermission(roles, route) { |
| if (route.meta && route.meta.roles) { |
| return roles.some(role => route.meta.roles.includes(role)) |
| } else { |
| return true |
| } |
| } |
| |
| |
| |
| |
| |
| |
| 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 |
| } |
| |
| const state = { |
| initRouterState: false |
| } |
| |
| const mutations = { |
| SET_INIT_ROUTER_STATE: (state, initRouterState) => { |
| state.initRouterState = initRouterState |
| } |
| } |
| |
| const actions = { |
| generateRoutes({ commit }, identity) { |
| return new Promise((resolve, reject) => { |
| let accessedRoutes = Routes[identity] |
| if (!accessedRoutes) { |
| reject(`identity ${identity} not exist!!!`) |
| } |
| commit('SET_INIT_ROUTER_STATE', true) |
| resolve(accessedRoutes) |
| }) |
| } |
| } |
| |
| export default { |
| namespaced: true, |
| state, |
| mutations, |
| actions |
| } |
| |
| |
| import router from './router' |
| import { getToken, getIdentity } from '@/utils/cookies' |
| |
| router.beforeEach(async (to, from, next) => { |
| if (getToken() && getIdentity()) { |
| ... |
| next() |
| } else { |
| try { |
| const accessRoutes = await store.dispatch('router/generateRoutes', getIdentity()) |
| |
| router.addRoutes(accessRoutes) |
| next({ ...to, replace: true }) |
| } catch (error) { |
| Message.error(error || 'Has Error') |
| } |
| } |
| } |
| }) |
| |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步