htao-common
Version:
通用
269 lines (259 loc) • 8.2 kB
JavaScript
import auth from '@/plugins/auth'
import store from '@/store'
import {
Message
} from 'element-ui'
import router, {
constantRoutes,
dynamicRoutes
} from '@/router'
import {
getRouters
} from '@/api/menu'
import Layout from '@/layout/index'
import ParentView from '@/components/ParentView'
import InnerLink from '@/layout/components/InnerLink'
import arrayToTree from "array-to-tree";
const permission = {
state: {
routes: [],
addRoutes: [],
defaultRoutes: [],
topbarRouters: [],
sidebarRouters: [],
judgeRouters: [],
buttonPer: [],
allPer: []
},
mutations: {
SET_ROUTES: (state, routes) => {
state.addRoutes = routes
state.routes = constantRoutes.concat(routes)
},
SET_DEFAULT_ROUTES: (state, routes) => {
state.defaultRoutes = constantRoutes.concat(routes)
},
SET_TOPBAR_ROUTES: (state, routes) => {
state.topbarRouters = routes
},
SET_SIDEBAR_ROUTERS: (state, routes) => {
state.sidebarRouters = routes
},
SET_PER_ROUTER: (state, routes) => {
state.judgeRouters = routes
},
SET_BUTTON_PER: (state, permissions) => {
state.buttonPer = permissions
},
SET_All_PER: (state, permissions) => {
state.allPer = permissions
},
},
actions: {
// 生成路由
GenerateRoutes({
commit
}) {
return new Promise(resolve => {
// 向后端请求路由数据
getRouters({
platform: 1
}).then(res => {
if (res.code !== '200') {
Message({
message: '该用户没有角色,请分配!',
type: 'error',
})
setTimeout(() => {
//需要定时执行的代码
store.dispatch('LogOut').then(() => {
const path = sessionStorage.getItem('getPath')
location.href = path === null ? '' : path
})
}, 2000)
}
if (res.data == null || res.data.size == 0) {
Message({
message: '该用户角色没有分配资源,请分配!',
type: 'error',
})
setTimeout(() => {
//需要定时执行的代码
store.dispatch('LogOut').then(() => {
const path = sessionStorage.getItem('getPath')
location.href = path === null ? '' : path
})
}, 2000)
} else {
const buttonPer = (res.data.filter(item => item.resourceType === '2')).map(item => item.resourceName)
commit('SET_BUTTON_PER', buttonPer)
const allPer = (res.data.filter(item => item.resourceType === '1'))
commit('SET_All_PER', allPer)
let arr = res.data.filter(item => item.resourceType !== '2')
commit('SET_PER_ROUTER', arr)
arr.forEach(item => {
item.a = item.url
item.redirect = 'noredirect'
item.meta = {
title: item.resourceName,
icon: item.icon,
"noCache": false,
"link": null
}
if (item.id == 0) {
item.name = item.path.slice(1)
item.alwaysShow = true
} else {
item.name = item.path
}
if (item.resourceType === '0') {
item.a = 'Layout'
}
})
arr = arr.sort((a, b) => {
return a.sortNum - b.sortNum
})
const result = arrayToTree(arr, {
parentProperty: "parentId",
customID: "id",
childrenProperty: "children",
});
console.log(result, 'result')
// const result=listToTree(res.data)
const sdata = JSON.parse(JSON.stringify(result))
const rdata = JSON.parse(JSON.stringify(result))
const sidebarRoutes = filterAsyncRouter(sdata)
const rewriteRoutes = filterAsyncRouter(rdata, false, true)
const asyncRoutes = filterDynamicRoutes(dynamicRoutes);
// console.log(asyncRoutes,'asyncRoutes')
rewriteRoutes.push({
path: '*',
redirect: '/404',
hidden: true
})
router.addRoutes(asyncRoutes);
commit('SET_ROUTES', rewriteRoutes)
commit('SET_SIDEBAR_ROUTERS', constantRoutes.concat(sidebarRoutes))
commit('SET_DEFAULT_ROUTES', sidebarRoutes)
commit('SET_TOPBAR_ROUTES', sidebarRoutes)
resolve(rewriteRoutes)
// }).catch(err=>{})
// },reject=>{console.log(err)})
}
})
})
}
}
}
// 遍历后台传来的路由字符串,转换为组件对象
function filterAsyncRouter(asyncRouterMap, lastRouter = false, type = false) {
return asyncRouterMap.filter(route => {
if (type && route.children) {
route.children = filterChildren(route.children)
}
if (route.a) {
// Layout ParentView 组件特殊处理
if (route.a === 'Layout') {
route.component = Layout
} else if (route.a === 'ParentView') {
route.component = ParentView
} else if (route.a === 'InnerLink') {
route.component = InnerLink
} else {
route.component = loadView(route.url)
}
}
if (route.children != null && route.children && route.children.length) {
route.children = filterAsyncRouter(route.children, route, type)
} else {
delete route['children']
delete route['redirect']
}
return true
})
}
function filterChildren(childrenMap, lastRouter = false) {
var children = []
childrenMap.forEach((el, index) => {
if (el.children && el.children.length) {
if (el.component === 'ParentView' && !lastRouter) {
el.children.forEach(c => {
c.path = el.path + '/' + c.path
if (c.children && c.children.length) {
children = children.concat(filterChildren(c.children, c))
return
}
children.push(c)
})
return
}
}
if (lastRouter) {
el.path = lastRouter.path + '/' + el.path
}
children = children.concat(el)
})
return children
}
// 动态路由遍历,验证是否具备权限
export function filterDynamicRoutes(routes) {
const res = []
// console.log(routes,'routes')
routes.forEach(route => {
res.push(route)
if (route.permissions) {
if (auth.hasPermiOr(route.permissions)) {
res.push(route)
}
} else if (route.roles) {
if (auth.hasRoleOr(route.roles)) {
res.push(route)
}
}
})
return res
}
export const loadView = (view) => {
if (process.env.NODE_ENV === 'development') {
return (resolve) => require([`@/views/${view}`], resolve)
} else {
// 使用 import 实现生产环境的路由懒加载
return () => import(`@/views/${view}`)
}
}
export const listToTree = (list) => {
debugger
var arr = []
let items = {}
var idsStr = ''
// 获取每个节点的直属子节点(是直属,不是所有子节点)
for (let i = 0; i < list.length; i++) {
let key = list[i].parentId
if (items[key]) {
items[key].push(list[i])
} else {
items[key] = []
items[key].push(list[i])
}
idsStr += idsStr === '' ? list[i].menuId : ',' + list[i].menuId
}
for (var key in items) {
if (idsStr.indexOf(key) === -1) { //找到最大的父节点key
arr = formatTree(items, key)
}
}
console.log(arr)
return arr
}
function formatTree(items, parentId) {
let result = []
if (!items[parentId]) {
return result
}
for (let t of items[parentId]) {
t.children = formatTree(items, t.menuId) //递归获取children
result.push(t)
}
return result
}
export default permission