routeHelper.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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. import { getTenantId, getToken } from '/@/utils/auth';
  8. import { URL_HASH_TAB, _eval } from '/@/utils';
  9. //引入online lib路由
  10. import { packageViews } from '/@/utils/monorepo/dynamicRouter';
  11. import { useI18n } from '/@/hooks/web/useI18n';
  12. export type LayoutMapKey = 'LAYOUT';
  13. const IFRAME = () => import('/@/views/sys/iframe/FrameBlank.vue');
  14. // const IFRAME = () => import('/@/views/sys/iframe/index.vue');
  15. const LayoutContent = () => import('/@/layouts/default/content/index.vue');
  16. const QIANKUN_NEED_AIR = () => import('/@/components/vent/micro/needAir.vue');
  17. const QIANKUN_VENT_MODAL = () => import('/@/components/vent/micro/ventModal.vue');
  18. const LayoutMap = new Map<string, () => Promise<typeof import('*.vue')>>();
  19. LayoutMap.set('LAYOUT', LAYOUT);
  20. LayoutMap.set('IFRAME', IFRAME);
  21. //微前端qiankun
  22. LayoutMap.set('LayoutsContent', LayoutContent);
  23. LayoutMap.set('VENTMODAL', QIANKUN_VENT_MODAL);
  24. LayoutMap.set('NEEDAIR', QIANKUN_NEED_AIR);
  25. let dynamicViewsModules: Record<string, () => Promise<Recordable>>;
  26. let microViews: Record<string, () => Promise<Recordable>>;
  27. // Dynamic introduction
  28. function asyncImportRoute(routes: AppRouteRecordRaw[] | undefined) {
  29. if (!dynamicViewsModules) {
  30. microViews = import.meta.glob('../../components/vent/micro/**/*.{vue,tsx}');
  31. dynamicViewsModules = import.meta.glob('../../views/**/*.{vue,tsx}');
  32. //合并online lib路由
  33. dynamicViewsModules = Object.assign({}, dynamicViewsModules, packageViews, microViews);
  34. }
  35. if (!routes) return;
  36. routes.forEach((item) => {
  37. //【jeecg-boot/issues/I5N2PN】左侧动态菜单怎么做国际化处理 2022-10-09
  38. //菜单支持国际化翻译
  39. if (item?.meta?.title) {
  40. const { t } = useI18n();
  41. if (item.meta.title.includes("t('") && t) {
  42. // update-begin--author:liaozhiyang---date:20230906---for:【QQYUN-6390】eval替换成new Function,解决build警告
  43. item.meta.title = new Function('t', `return ${item.meta.title}`)(t);
  44. // update-end--author:liaozhiyang---date:20230906---for:【QQYUN-6390】eval替换成new Function,解决build警告
  45. }
  46. }
  47. // update-begin--author:sunjianlei---date:20210918---for:适配旧版路由选项 --------
  48. // @ts-ignore 适配隐藏路由
  49. if (item?.hidden) {
  50. item.meta.hideMenu = true;
  51. //是否隐藏面包屑
  52. item.meta.hideBreadcrumb = true;
  53. }
  54. // @ts-ignore 添加忽略路由配置
  55. if (item?.route == 0) {
  56. item.meta.ignoreRoute = true;
  57. }
  58. // @ts-ignore 添加是否缓存路由配置
  59. item.meta.ignoreKeepAlive = !item?.meta.keepAlive;
  60. const token = getToken();
  61. const tenantId = getTenantId();
  62. // URL支持{{ window.xxx }}占位符变量
  63. //update-begin---author:wangshuai ---date:20220711 for:[VUEN-1638]菜单tenantId需要动态生成------------
  64. item.component = (item.component || '')
  65. .replace(/{{([^}}]+)?}}/g, (s1, s2) => _eval(s2))
  66. .replace('${token}', token)
  67. .replace('${tenantId}', tenantId);
  68. //update-end---author:wangshuai ---date:20220711 for:[VUEN-1638]菜单tenantId需要动态生成------------
  69. // 适配 iframe
  70. if (/^\/?http(s)?/.test(item.component as string)) {
  71. item.component = item.component.substring(1, item.component.length);
  72. }
  73. if (/^http(s)?/.test(item.component as string)) {
  74. if (item.meta?.internalOrExternal) {
  75. // @ts-ignore 外部打开
  76. item.path = item.component;
  77. // update-begin--author:sunjianlei---date:20220408---for: 【VUEN-656】配置外部网址打不开,原因是带了#号,需要替换一下
  78. item.path = item.path.replace('#', URL_HASH_TAB);
  79. // update-end--author:sunjianlei---date:20220408---for: 【VUEN-656】配置外部网址打不开,原因是带了#号,需要替换一下
  80. } else {
  81. // @ts-ignore 内部打开
  82. item.meta.frameSrc = item.component;
  83. }
  84. delete item.component;
  85. }
  86. // update-end--author:sunjianlei---date:20210918---for:适配旧版路由选项 --------
  87. if (!item.component && item.meta?.frameSrc) {
  88. item.component = 'IFRAME';
  89. }
  90. let { component, name } = item;
  91. const { children } = item;
  92. if (component) {
  93. const layoutFound = LayoutMap.get(component.toUpperCase());
  94. if (layoutFound) {
  95. console.log('6666666666666666', layoutFound, component);
  96. item.component = layoutFound;
  97. } else {
  98. // update-end--author:zyf---date:20220307--for:VUEN-219兼容后台返回动态首页,目的适配跟v2版本配置一致 --------
  99. if (component.indexOf('dashboard/') > -1) {
  100. //当数据标sys_permission中component没有拼接index时前端需要拼接
  101. if (component.indexOf('/index') < 0) {
  102. component = component + '/index';
  103. }
  104. }
  105. // update-end--author:zyf---date:20220307---for:VUEN-219兼容后台返回动态首页,目的适配跟v2版本配置一致 --------
  106. item.component = dynamicImport(dynamicViewsModules, component as string);
  107. }
  108. } else if (name) {
  109. item.component = getParentLayout();
  110. }
  111. children && asyncImportRoute(children);
  112. });
  113. // console.log('------------------------>', routes);
  114. }
  115. function dynamicImport(dynamicViewsModules: Record<string, () => Promise<Recordable>>, component: string) {
  116. const keys = Object.keys(dynamicViewsModules);
  117. const matchKeys = keys.filter((key) => {
  118. let k = '';
  119. if (key.startsWith('../../components')) {
  120. k = key.replace('../../components', '');
  121. } else {
  122. k = key.replace('../../views', '');
  123. }
  124. const startFlag = component.startsWith('/');
  125. const endFlag = component.endsWith('.vue') || component.endsWith('.tsx');
  126. const startIndex = startFlag ? 0 : 1;
  127. const lastIndex = endFlag ? k.length : k.lastIndexOf('.');
  128. return k.substring(startIndex, lastIndex) === component;
  129. });
  130. if (matchKeys?.length === 1) {
  131. const matchKey = matchKeys[0];
  132. return dynamicViewsModules[matchKey];
  133. } else if (matchKeys?.length > 1) {
  134. warn(
  135. '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'
  136. );
  137. return;
  138. }
  139. }
  140. // Turn background objects into routing objects
  141. export function transformObjToRoute<T = AppRouteModule>(routeList: AppRouteModule[]): T[] {
  142. routeList.forEach((route) => {
  143. const component = route.component as string;
  144. if (component) {
  145. if (component.toUpperCase() === 'LAYOUT') {
  146. route.component = LayoutMap.get(component.toUpperCase());
  147. } else {
  148. route.children = [cloneDeep(route)];
  149. route.component = LAYOUT;
  150. route.name = `${route.name}Parent`;
  151. route.path = '';
  152. const meta = route.meta || {};
  153. meta.single = true;
  154. meta.affix = false;
  155. route.meta = meta;
  156. }
  157. } else {
  158. warn('请正确配置路由:' + route?.name + '的component属性');
  159. }
  160. route.children && asyncImportRoute(route.children);
  161. });
  162. return routeList as unknown as T[];
  163. }
  164. /**
  165. * 将多级路由转换为二级
  166. */
  167. export function flatMultiLevelRoutes(routeModules: AppRouteModule[]) {
  168. const modules: AppRouteModule[] = cloneDeep(routeModules);
  169. for (let index = 0; index < modules.length; index++) {
  170. const routeModule = modules[index];
  171. if (!isMultipleRoute(routeModule)) {
  172. continue;
  173. }
  174. promoteRouteLevel(routeModule);
  175. }
  176. return modules;
  177. }
  178. //提升路由级别
  179. function promoteRouteLevel(routeModule: AppRouteModule) {
  180. // Use vue-router to splice menus
  181. let router: Router | null = createRouter({
  182. routes: [routeModule as unknown as RouteRecordNormalized],
  183. history: createWebHashHistory(),
  184. });
  185. const routes = router.getRoutes();
  186. addToChildren(routes, routeModule.children || [], routeModule);
  187. router = null;
  188. routeModule.children = routeModule.children?.map((item) => omit(item, 'children'));
  189. }
  190. // Add all sub-routes to the secondary route
  191. function addToChildren(routes: RouteRecordNormalized[], children: AppRouteRecordRaw[], routeModule: AppRouteModule) {
  192. for (let index = 0; index < children.length; index++) {
  193. const child = children[index];
  194. const route = routes.find((item) => item.name === child.name);
  195. if (!route) {
  196. continue;
  197. }
  198. routeModule.children = routeModule.children || [];
  199. if (!routeModule.children.find((item) => item.name === route.name)) {
  200. routeModule.children?.push(route as unknown as AppRouteModule);
  201. }
  202. if (child.children?.length) {
  203. addToChildren(routes, child.children, routeModule);
  204. }
  205. }
  206. }
  207. // Determine whether the level exceeds 2 levels
  208. function isMultipleRoute(routeModule: AppRouteModule) {
  209. if (!routeModule || !Reflect.has(routeModule, 'children') || !routeModule.children?.length) {
  210. return false;
  211. }
  212. const children = routeModule.children;
  213. let flag = false;
  214. for (let index = 0; index < children.length; index++) {
  215. const child = children[index];
  216. if (child.children?.length) {
  217. flag = true;
  218. break;
  219. }
  220. }
  221. return flag;
  222. }
  223. /**
  224. * 组件地址前加斜杠处理
  225. * @updateBy:lsq
  226. * @updateDate:2021-09-08
  227. */
  228. export function addSlashToRouteComponent(routeList: AppRouteRecordRaw[]) {
  229. routeList.forEach((route) => {
  230. if (route.path.startsWith('/subSysmodal')) {
  231. route.path = '/micro-vent-3dModal' + route.path;
  232. route.component = 'VENTMODAL';
  233. }
  234. const component = route.component as string;
  235. if (component) {
  236. const layoutFound = LayoutMap.get(component);
  237. if (!layoutFound) {
  238. route.component = component.startsWith('/') ? component : `/${component}`;
  239. }
  240. }
  241. route.children && addSlashToRouteComponent(route.children);
  242. });
  243. console.log('9999999999999999999999999999>', routeList);
  244. return routeList as unknown as T[];
  245. }