import { asyncRoutes, commonRoutes } from '@/router'
|
import Layout from '@/layout'
|
|
// 判断是否有权限
|
function hasPermission(roles, route) {
|
if (route.meta && route.meta.role) {
|
return roles.some(role => route.meta.role.includes(role))
|
} else {
|
return true
|
}
|
}
|
|
/**
|
* 把后台返回菜单组装成routes要求的格式
|
* @param {*} routes
|
*/
|
export function getAsyncRoutes(routes2, menu) {
|
const menuCode = []// 将后端code取出存成数组形式
|
menu.forEach(item => {
|
menuCode.push(item.code)
|
if (item.children && item.children.length > 0) {
|
item.children.forEach(it => {
|
menuCode.push(it.code)
|
})
|
}
|
})
|
|
const routes = routes2
|
const newRoutes = []
|
|
routes.forEach(item => {
|
if (menuCode.includes(item.code) && item.children && item.children.length > 0) {
|
console.log(item)
|
const children = []
|
let flag = false// 判断是否有children存进去
|
item.children.forEach(it => {
|
if (menuCode.includes(it.code)) {
|
children.push(it)
|
flag = true
|
}
|
})
|
if (flag) {
|
newRoutes.push({
|
alwaysShow: item.alwaysShow,
|
code: item.code,
|
name: item.name,
|
path: item.path,
|
redirect: item.redirect,
|
component: item.component,
|
children: children,
|
meta: item.meta
|
})
|
}
|
}
|
})
|
|
newRoutes.push({ path: '*', redirect: '/404', hidden: true })
|
|
return newRoutes
|
}
|
|
// 过滤出有权限的路由
|
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 = {
|
routes: commonRoutes,
|
addRouters: []
|
}
|
|
const mutations = {
|
SET_ROUTES: (state, routes) => {
|
state.addRouters = routes
|
state.routes = commonRoutes.concat(routes)
|
}
|
}
|
|
const actions = {
|
generateRoutes({ commit }, menu) {
|
return new Promise(resolve => {
|
const newRoutes = getAsyncRoutes(asyncRoutes, menu)
|
console.log(newRoutes, 2)
|
commit('SET_ROUTES', newRoutes)
|
resolve(newRoutes)
|
})
|
}
|
}
|
|
export default {
|
namespaced: true,
|
state,
|
mutations,
|
actions
|
}
|