import { asyncRoutes, constantRoutes } from '@/router' import Layout from "@/layout/index"; import axiosMethods from "../../axios"; import router, { resetRouter } from '@/router' /** * * @param {*} router * @param {*} authInfo */ function checkAuth(router, authInfo) { // 判断当前路由在权限数组中是否存在 if (router.meta) { const metaInfo = router.meta console.log(JSON.stringify(metaInfo)) if (!metaInfo.requiresAuth) { return true } else { if (metaInfo.index == 0) { return !!authInfo[metaInfo.type] } else if (metaInfo.index == 1) { if (authInfo[metaInfo.type]) { return !!authInfo[metaInfo.type][metaInfo.subType] } return false } else { var typeAuth = authInfo[metaInfo.type] for (let index = 0; index < metaInfo.subType.length; index++) { const field = metaInfo.subType[index] typeAuth = typeAuth[field] if (typeAuth && metaInfo.subType.length - 1 == index) { return true } else if (!typeAuth) { return false } } } } } return true } /** * * @param {*} routers * @param {*} authInfo */ const filterAsyncRouter = function (routers, authInfo) { const res = [] routers.forEach(router => { const tmp = { ...router } if (checkAuth(tmp, authInfo)) { if (tmp.children) { tmp.children = filterAsyncRouter(tmp.children, authInfo) } res.push(tmp) } }) return res } /** * 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 = { routes: [], addRoutes: [], sysRouters: { name: 'sys', children: [] }, firstRouters: { name: 'first', children: [] }, manageRouters: { name: 'manager', children: [] }, } const mutations = { SET_ROUTES: (state, routes) => { state.addRoutes = routes state.routes = constantRoutes.concat(routes) for (let index = 0; index < routes.length; index++) { const element = routes[index] if (element.name == 'first') { state.firstRouters = element } else if (element.name == 'manager') { state.manageRouters = element } } }, /** * 客户管理待办消息数 */ // SET_CRMROUTERSNUM: (state, num) => { // const messageItem = state.routes.children[1] // alert(messageItem) // messageItem.meta.num = num // Vue.set(state.routes.children, 1, messageItem) // } } const actions = { generateRoutes({ commit }, roles) { return new Promise(resolve => { let accessedRoutes if (roles.includes('admin')) { accessedRoutes = asyncRoutes || [] } else { accessedRoutes = filterAsyncRoutes(asyncRoutes, roles) } commit('SET_ROUTES', accessedRoutes) resolve(accessedRoutes) }) }, } export default { namespaced: true, state, mutations, actions }