vue - 路由权限控制
vue - 路由权限控制
router 目录结构
└── router
├── modules
│ ├── administrator.js
│ ├── [identity].js
│ └── xxx.js
└── index.js
身份路由导出
// \src\router\index.js
export { default as [identity] } from './modules/[identity]';
根据权限生成路由
// main.js
import './permission';
// \src\store\modules\router.js
import { [identity1], [identity2] } from '@/router'
const Routes = {
identity1: [identity1],
identity2: [identity2]
}
/**
* 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
}
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
}
// permission.js
import router from './router'
import { getToken, getIdentity } from '@/utils/cookies' // get token from cookie
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')
}
}
}
})
Lee2