| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114 |
- import { RouteRecordRaw } from 'vue-router'
- import { AuthType } from '@/constants/menu'
- import { useRouterStore } from '@/stores'
- import router from '../router'
- import Page from '../components/layouts/page/index.vue'
- export default new (class {
- /** 防止动态路由无限加载 */
- isReady = false;
- /** 已注册的路由 */
- private registeredRouteNames: string[] = [];
- /**
- * 添加404页面
- */
- private addNotFound() {
- router.addRoute({
- path: '/:pathMatch(.*)*',
- name: 'NotFound',
- component: Page,
- meta: {
- title: '系统错误'
- },
- children: [
- {
- path: '',
- name: 'NotFoundIndex',
- component: () => import('../views/error/404.vue'),
- meta: {
- title: '404'
- }
- }
- ]
- })
- }
- /**
- * 移除404页面
- */
- private removeNotFound() {
- if (router.hasRoute('NotFound')) {
- router.removeRoute('NotFound');
- }
- }
- /**
- * 动态添加路由
- * @param routes
- * @param parentName
- */
- private addRoutes(routes: Model.MenusRsp[], parentName = '') {
- routes.forEach((item) => {
- if (item.authType === AuthType.Menu && item.component) {
- let component;
- switch (item.component) {
- case 'Page': {
- component = Page;
- break;
- }
- default: {
- const componentString = item.component.replace(/^\/+/, ''); // 过滤字符串前面所有 '/' 字符
- const componentPath = componentString.replace(/\.\w+$/, ''); // 过滤后缀名,为了让 import 加入 .vue ,不然会有警告提示...
- component = () => import('../' + componentPath + '.vue');
- }
- }
- const route: RouteRecordRaw = {
- path: (item.url.startsWith('/') ? '' : '/') + item.url,
- name: item.resourceCode,
- component,
- meta: {
- title: item.title,
- icon: item.icon,
- remark: item.remark,
- keepAlive: true, // 默认缓存页面
- },
- }
- parentName ? router.addRoute(parentName, route) : router.addRoute(route);
- if (item.parentCode === '') {
- this.registeredRouteNames.push(item.resourceCode); // 添加一级路由到注册列表
- }
- if (item.children && item.children.length) {
- this.addRoutes(item.children, item.resourceCode);
- }
- }
- })
- }
- /**
- * 移除所有已注册的路由
- */
- unregisterRoutes() {
- this.removeNotFound();
- this.registeredRouteNames.forEach((name) => {
- router.removeRoute(name);
- })
- this.registeredRouteNames = [];
- }
- /**
- * 注册路由
- * @returns
- */
- registerRoutes() {
- const routerStore = useRouterStore();
- this.addNotFound();
- this.addRoutes(routerStore.userRoutes);
- this.isReady = true;
- }
- })
|