import { RouteRecordRaw } from 'vue-router' import { AuthType } from '@/constants/menu' import { useMenuStore } from '@/stores' import router from '../router' export default new (class { /** 防止动态路由无限加载 */ isReady = false; /** * 添加404页面 */ private addNotFound() { router.addRoute({ path: '/:pathMatch(.*)*', name: 'Error', component: () => import('../views/error/404.vue'), }) } /** * 动态添加路由 * @param routes * @param parentName */ private addRoutes(routes: Ermcp.UserMenu[], parentName = '') { routes.forEach((item) => { if (item.authType === AuthType.Menu && item.component) { let component; switch (item.component) { case 'Page': { component = () => import('../components/layouts/page/index.vue'); break; } case 'Main': { component = () => import('../components/layouts/main/index.vue'); break; } default: { const componentString = item.component.replace(/^\/+/, ''); // 过滤字符串前面所有 '/' 字符 const componentPath = componentString.replace(/\.\w+$/, ''); // 过滤后缀名,为了让 import 加入 .vue ,不然会有警告提示... component = () => import('../' + componentPath + '.vue'); } } const route: RouteRecordRaw = { path: item.url, name: item.code, component, meta: { title: item.title, icon: item.icon, remark: item.remark, }, } parentName ? router.addRoute(parentName, route) : router.addRoute(route); if (item.children && item.children.length) { this.addRoutes(item.children, item.code); } } }) } /** * 注册路由 * @returns */ registerRoutes() { const { userMenus } = useMenuStore(); this.addNotFound(); this.addRoutes(userMenus.value); this.isReady = true; } })