routeHelper.ts 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  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. // 将背景对象变成路由对象
  64. export function transformObjToRoute<T = AppRouteModule>(routeList: AppRouteModule[]): T[] {
  65. routeList.forEach((route) => {
  66. const component = route.component as string;
  67. if (component) {
  68. if (component.toUpperCase() === 'LAYOUT') {
  69. route.component = LayoutMap.get(component.toUpperCase());
  70. } else {
  71. route.children = [cloneDeep(route)];
  72. route.component = LAYOUT;
  73. //某些情况下如果name如果没有值, 多个一级路由菜单会导致页面404
  74. if (!route.name || !route.menuName) {
  75. warn('找不到菜单对应的name或menuName, 请检查数据!');
  76. }
  77. route.name = `${route.name || route.menuName}Parent`;
  78. route.path = '';
  79. const meta = route.meta || {};
  80. meta.single = true;
  81. meta.affix = false;
  82. route.meta = meta;
  83. }
  84. } else {
  85. warn('请正确配置路由:' + route?.name + '的component属性');
  86. }
  87. route.children && asyncImportRoute(route.children);
  88. });
  89. return routeList as unknown as T[];
  90. }
  91. /**
  92. * Convert multi-level routing to level 2 routing
  93. * 将多级路由转换为 2 级路由
  94. */
  95. export function flatMultiLevelRoutes(routeModules: AppRouteModule[]) {
  96. const modules: AppRouteModule[] = cloneDeep(routeModules);
  97. for (let index = 0; index < modules.length; index++) {
  98. const routeModule = modules[index];
  99. // 判断级别是否 多级 路由
  100. if (!isMultipleRoute(routeModule)) {
  101. // 声明终止当前循环, 即跳过此次循环,进行下一轮
  102. continue;
  103. }
  104. // 路由等级提升
  105. promoteRouteLevel(routeModule);
  106. }
  107. return modules;
  108. }
  109. // Routing level upgrade
  110. // 路由等级提升
  111. function promoteRouteLevel(routeModule: AppRouteModule) {
  112. // Use vue-router to splice menus
  113. // 使用vue-router拼接菜单
  114. // createRouter 创建一个可以被 Vue 应用程序使用的路由实例
  115. let router: Router | null = createRouter({
  116. routes: [routeModule as unknown as RouteRecordNormalized],
  117. history: createWebHashHistory(),
  118. });
  119. // getRoutes: 获取所有 路由记录的完整列表。
  120. const routes = router.getRoutes();
  121. // 将所有子路由添加到二级路由
  122. addToChildren(routes, routeModule.children || [], routeModule);
  123. router = null;
  124. // omit lodash的函数 对传入的item对象的children进行删除
  125. routeModule.children = routeModule.children?.map((item) => omit(item, 'children'));
  126. }
  127. // Add all sub-routes to the secondary route
  128. // 将所有子路由添加到二级路由
  129. function addToChildren(
  130. routes: RouteRecordNormalized[],
  131. children: AppRouteRecordRaw[],
  132. routeModule: AppRouteModule,
  133. ) {
  134. for (let index = 0; index < children.length; index++) {
  135. const child = children[index];
  136. const route = routes.find((item) => item.name === child.name);
  137. if (!route) {
  138. continue;
  139. }
  140. routeModule.children = routeModule.children || [];
  141. if (!routeModule.children.find((item) => item.name === route.name)) {
  142. routeModule.children?.push(route as unknown as AppRouteModule);
  143. }
  144. if (child.children?.length) {
  145. addToChildren(routes, child.children, routeModule);
  146. }
  147. }
  148. }
  149. // Determine whether the level exceeds 2 levels
  150. // 判断级别是否超过2级
  151. function isMultipleRoute(routeModule: AppRouteModule) {
  152. // Reflect.has 与 in 操作符 相同, 用于检查一个对象(包括它原型链上)是否拥有某个属性
  153. if (!routeModule || !Reflect.has(routeModule, 'children') || !routeModule.children?.length) {
  154. return false;
  155. }
  156. const children = routeModule.children;
  157. let flag = false;
  158. for (let index = 0; index < children.length; index++) {
  159. const child = children[index];
  160. if (child.children?.length) {
  161. flag = true;
  162. break;
  163. }
  164. }
  165. return flag;
  166. }