import { constantRoutes } from '@/router' import { permissions } from '@/api/me' import Layout from '@/layout' import Nested from '@/layout/nested.vue' import Wujie from '@/views/wujie' import SiderbarLayout from '@/layout/SiderbarLayout.vue' const loadView = (view) => { return (resolve) => require([`@/views${view}`], resolve) } const componentHandle = (path, route) => { if (/^#+/.test(path) && route.pid === 0 && route.children.length <= 1) { return Layout } else if (/^#+/.test(path) && route.pid === 0 && route.children.length > 1) { return SiderbarLayout } else if (/^#+/.test(path) && route.pid !== 0) { return Nested } else if (/^\/./.test(path)) { return loadView(path) } else { return Wujie } } export function filterAsyncRoutes(routes) { const res = [] routes.forEach(route => { if (!route.visible) return const tmp = { key: `key-${route.id}`, path: route.path === '#' ? '' : route.path, component: componentHandle(route.path, route), name: route.name, hidden: !route.visible, meta: { id: route.id, title: route.title, icon: route.icon, guard: route.guard_name, folder: route.folder, isModule: !/^\/./.test(route.path), // TODO:修改地址 // moduleUri: /^\/./.test(route.path) ? '' : `https://cz-hjjc.115.langye.net/${route.path}`, moduleUri: /^\/./.test(route.path) ? '' : `/${route.path}`, moduleName: /^\/./.test(route.path) ? '' : route.path } } if (route.children && route.children instanceof Array && route.children.length > 0) { tmp.children = filterAsyncRoutes(route.children) } res.push(tmp) }) return res } const state = { routes: [], addRoutes: [] } const mutations = { SET_ROUTES: (state, routes) => { state.addRoutes = routes state.routes = constantRoutes.concat(routes) }, RESET_ADD_ROUTES: (state) => { state.addRoutes = [] } } const actions = { generateRoutes({ commit }, roles) { return new Promise(async(resolve, reject) => { try { const routes = await permissions() const accessedRoutes = filterAsyncRoutes(routes) // 把404拦截放在最后匹配 accessedRoutes.push({ path: '*', redirect: '/404', hidden: true }) commit('SET_ROUTES', accessedRoutes) resolve(accessedRoutes) } catch (err) { reject(err) } }) } } export default { namespaced: true, state, mutations, actions }