routeHelper.ts 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. import type { AppRouteModule, AppRouteRecordRaw } from '/@/router/types';
  2. import type { Router, RouteRecordNormalized } from 'vue-router';
  3. import { getParentLayout, LAYOUT, EXCEPTION_COMPONENT } from '/@/router/constant';
  4. import { cloneDeep, omit } from 'lodash-es';
  5. import { warn } from '/@/utils/log';
  6. import { createRouter, createWebHashHistory } from 'vue-router';
  7. export type LayoutMapKey = 'LAYOUT';
  8. const IFRAME = () => import('/@/views/sys/iframe/FrameBlank.vue');
  9. const LayoutMap = new Map<string, () => Promise<typeof import('*.vue')>>();
  10. LayoutMap.set('LAYOUT', LAYOUT);
  11. LayoutMap.set('IFRAME', IFRAME);
  12. let dynamicViewsModules: Record<string, () => Promise<Recordable>>;
  13. // Dynamic introduction
  14. function asyncImportRoute(routes: AppRouteRecordRaw[] | undefined) {
  15. dynamicViewsModules = dynamicViewsModules || import.meta.glob('../../views/**/*.{vue,tsx}');
  16. if (!routes) return;
  17. routes.forEach((item) => {
  18. if (!item.component && item.meta?.frameSrc) {
  19. item.component = 'IFRAME';
  20. }
  21. const { component, name } = item;
  22. const { children } = item;
  23. if (component) {
  24. const layoutFound = LayoutMap.get(component.toUpperCase());
  25. if (layoutFound) {
  26. item.component = layoutFound;
  27. } else {
  28. item.component = dynamicImport(dynamicViewsModules, component as string);
  29. }
  30. } else if (name) {
  31. item.component = getParentLayout();
  32. }
  33. children && asyncImportRoute(children);
  34. });
  35. }
  36. function dynamicImport(
  37. dynamicViewsModules: Record<string, () => Promise<Recordable>>,
  38. component: string,
  39. ) {
  40. const keys = Object.keys(dynamicViewsModules);
  41. const matchKeys = keys.filter((key) => {
  42. const k = key.replace('../../views', '');
  43. const startFlag = component.startsWith('/');
  44. const endFlag = component.endsWith('.vue') || component.endsWith('.tsx');
  45. const startIndex = startFlag ? 0 : 1;
  46. const lastIndex = endFlag ? k.length : k.lastIndexOf('.');
  47. return k.substring(startIndex, lastIndex) === component;
  48. });
  49. if (matchKeys?.length === 1) {
  50. const matchKey = matchKeys[0];
  51. return dynamicViewsModules[matchKey];
  52. } else if (matchKeys?.length > 1) {
  53. warn(
  54. 'Please do not create `.vue` and `.TSX` files with the same file name in the same hierarchical directory under the views folder. This will cause dynamic introduction failure',
  55. );
  56. return;
  57. } else {
  58. warn('在src/views/下找不到`' + component + '.vue` 或 `' + component + '.tsx`, 请自行创建!');
  59. return EXCEPTION_COMPONENT;
  60. }
  61. }
  62. // Turn background objects into routing objects
  63. export function transformObjToRoute<T = AppRouteModule>(routeList: AppRouteModule[]): T[] {
  64. routeList.forEach((route) => {
  65. const component = route.component as string;
  66. if (component) {
  67. if (component.toUpperCase() === 'LAYOUT') {
  68. route.component = LayoutMap.get(component.toUpperCase());
  69. } else {
  70. route.children = [cloneDeep(route)];
  71. route.component = LAYOUT;
  72. route.name = `${route.name}Parent`;
  73. route.path = '';
  74. const meta = route.meta || {};
  75. meta.single = true;
  76. meta.affix = false;
  77. route.meta = meta;
  78. }
  79. } else {
  80. warn('请正确配置路由:' + route?.name + '的component属性');
  81. }
  82. route.children && asyncImportRoute(route.children);
  83. });
  84. return routeList as unknown as T[];
  85. }
  86. /**
  87. * Convert multi-level routing to level 2 routing
  88. */
  89. export function flatMultiLevelRoutes(routeModules: AppRouteModule[]) {
  90. const modules: AppRouteModule[] = cloneDeep(routeModules);
  91. for (let index = 0; index < modules.length; index++) {
  92. const routeModule = modules[index];
  93. if (!isMultipleRoute(routeModule)) {
  94. continue;
  95. }
  96. promoteRouteLevel(routeModule);
  97. }
  98. return modules;
  99. }
  100. // Routing level upgrade
  101. function promoteRouteLevel(routeModule: AppRouteModule) {
  102. // Use vue-router to splice menus
  103. let router: Router | null = createRouter({
  104. routes: [routeModule as unknown as RouteRecordNormalized],
  105. history: createWebHashHistory(),
  106. });
  107. const routes = router.getRoutes();
  108. addToChildren(routes, routeModule.children || [], routeModule);
  109. router = null;
  110. routeModule.children = routeModule.children?.map((item) => omit(item, 'children'));
  111. }
  112. // Add all sub-routes to the secondary route
  113. function addToChildren(
  114. routes: RouteRecordNormalized[],
  115. children: AppRouteRecordRaw[],
  116. routeModule: AppRouteModule,
  117. ) {
  118. for (let index = 0; index < children.length; index++) {
  119. const child = children[index];
  120. const route = routes.find((item) => item.name === child.name);
  121. if (!route) {
  122. continue;
  123. }
  124. routeModule.children = routeModule.children || [];
  125. if (!routeModule.children.find((item) => item.name === route.name)) {
  126. routeModule.children?.push(route as unknown as AppRouteModule);
  127. }
  128. if (child.children?.length) {
  129. addToChildren(routes, child.children, routeModule);
  130. }
  131. }
  132. }
  133. // Determine whether the level exceeds 2 levels
  134. function isMultipleRoute(routeModule: AppRouteModule) {
  135. if (!routeModule || !Reflect.has(routeModule, 'children') || !routeModule.children?.length) {
  136. return false;
  137. }
  138. const children = routeModule.children;
  139. let flag = false;
  140. for (let index = 0; index < children.length; index++) {
  141. const child = children[index];
  142. if (child.children?.length) {
  143. flag = true;
  144. break;
  145. }
  146. }
  147. return flag;
  148. }