dynamicRouter.ts 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. import { RouteRecordRaw } from 'vue-router'
  2. import { AuthType } from '@/constants/menu'
  3. import { useRouterStore } from '@/stores'
  4. import router from '../router'
  5. import Page from '../components/layouts/page/index.vue'
  6. export default new (class {
  7. /** 防止动态路由无限加载 */
  8. isReady = false;
  9. /** 已注册的路由 */
  10. private registeredRouteNames: string[] = [];
  11. /**
  12. * 添加404页面
  13. */
  14. private addNotFound() {
  15. router.addRoute({
  16. path: '/:pathMatch(.*)*',
  17. name: 'NotFound',
  18. component: Page,
  19. meta: {
  20. title: '系统错误'
  21. },
  22. children: [
  23. {
  24. path: '',
  25. name: 'NotFoundIndex',
  26. component: () => import('../views/error/404.vue'),
  27. meta: {
  28. title: '404'
  29. }
  30. }
  31. ]
  32. })
  33. }
  34. /**
  35. * 移除404页面
  36. */
  37. private removeNotFound() {
  38. if (router.hasRoute('NotFound')) {
  39. router.removeRoute('NotFound');
  40. }
  41. }
  42. /**
  43. * 动态添加路由
  44. * @param routes
  45. * @param parentName
  46. */
  47. private addRoutes(routes: Model.MenusRsp[], parentName = '') {
  48. routes.forEach((item) => {
  49. if (item.authType === AuthType.Menu && item.component) {
  50. let component;
  51. switch (item.component) {
  52. case 'Page': {
  53. component = Page;
  54. break;
  55. }
  56. default: {
  57. const componentString = item.component.replace(/^\/+/, ''); // 过滤字符串前面所有 '/' 字符
  58. const componentPath = componentString.replace(/\.\w+$/, ''); // 过滤后缀名,为了让 import 加入 .vue ,不然会有警告提示...
  59. component = () => import('../' + componentPath + '.vue');
  60. }
  61. }
  62. const route: RouteRecordRaw = {
  63. path: (item.url.startsWith('/') ? '' : '/') + item.url,
  64. name: item.resourceCode,
  65. component,
  66. meta: {
  67. title: item.title,
  68. icon: item.icon,
  69. remark: item.remark,
  70. keepAlive: true, // 默认缓存页面
  71. },
  72. }
  73. parentName ? router.addRoute(parentName, route) : router.addRoute(route);
  74. if (item.parentCode === '') {
  75. this.registeredRouteNames.push(item.resourceCode); // 添加一级路由到注册列表
  76. }
  77. if (item.children && item.children.length) {
  78. this.addRoutes(item.children, item.resourceCode);
  79. }
  80. }
  81. })
  82. }
  83. /**
  84. * 移除所有已注册的路由
  85. */
  86. unregisterRoutes() {
  87. this.removeNotFound();
  88. this.registeredRouteNames.forEach((name) => {
  89. router.removeRoute(name);
  90. })
  91. this.registeredRouteNames = [];
  92. }
  93. /**
  94. * 注册路由
  95. * @returns
  96. */
  97. registerRoutes() {
  98. const routerStore = useRouterStore();
  99. this.addNotFound();
  100. this.addRoutes(routerStore.userRoutes);
  101. this.isReady = true;
  102. }
  103. })