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
|
* @param {*} menu
|
*/
|
export function getAsyncRoutes(routes, menu) {
|
// menu 中flag "0" 表示 true "1"表示false
|
const menuCode = []// 将后端code取出存成数组形式
|
const menuNameAndCode = []// 将后端code与name取出存成数组形式
|
menu.forEach(item => {
|
if (item.flag === '0') {
|
menuCode.push(item.code)
|
menuNameAndCode.push({ code: item.code, name: item.name })
|
if (item.children && item.children.length > 0) {
|
item.children.forEach(it => {
|
if (it.flag === '0') {
|
menuCode.push(it.code)
|
menuNameAndCode.push({ code: it.code, name: it.name })
|
}
|
})
|
}
|
}
|
})
|
|
const newRoutes = [] // 新路由
|
|
routes.forEach(item => {
|
if (menuCode.includes(item.code) && item.children && item.children.length > 0) {
|
item.meta.title = menuNameAndCode.find(item2 => item2.code === item.code).name
|
const children = []
|
let flag = false// 判断是否有children存进去
|
item.children.forEach(it => {
|
if (menuCode.includes(it.code)) {
|
it.meta.title = menuNameAndCode.find(item2 => item2.code === it.code).name
|
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 => {
|
// console.log(menu, 'menu')
|
// // const newRoutes = getAsyncRoutes(asyncRoutes, menu)
|
// const arr = ['1001', '1002', '1004']
|
// const newRoutes = asyncRoutes.filter(i => {
|
// if (arr.includes(i.code)) {
|
// return i
|
// }
|
// })
|
|
const newRoutes = asyncRoutes
|
|
commit('SET_ROUTES', newRoutes)
|
resolve(newRoutes)
|
})
|
}
|
}
|
|
export default {
|
namespaced: true,
|
state,
|
mutations,
|
actions
|
}
|