generator-routers.ts 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. import { adminMenus } from '@/api/system/menu';
  2. import { constantRouterIcon } from './router-icons';
  3. import { RouteRecordRaw } from 'vue-router';
  4. import { Layout, ParentLayout } from '@/router/constant';
  5. import type { AppRouteRecordRaw } from '@/router/types';
  6. const Iframe = () => import('@/views/iframe/index.vue');
  7. const LayoutMap = new Map<string, () => Promise<typeof import('*.vue')>>();
  8. LayoutMap.set('LAYOUT', Layout);
  9. LayoutMap.set('IFRAME', Iframe);
  10. /**
  11. * 格式化 后端 结构信息并递归生成层级路由表
  12. * @param routerMap
  13. * @param parent
  14. * @returns {*}
  15. */
  16. export const routerGenerator = (routerMap, parent?): any[] => {
  17. return routerMap.map((item) => {
  18. const currentRouter: any = {
  19. // 路由地址 动态拼接生成如 /dashboard/workplace
  20. path: `${(parent && parent.path) || ''}/${item.path}`,
  21. // 路由名称,建议唯一
  22. name: item.name || '',
  23. // 该路由对应页面的 组件
  24. component: item.component,
  25. // meta: 页面标题, 菜单图标, 页面权限(供指令权限用,可去掉)
  26. meta: {
  27. ...item.meta,
  28. label: item.meta.title,
  29. icon: constantRouterIcon[item.meta.icon] || null,
  30. permissions: item.meta.permissions || null,
  31. },
  32. };
  33. // 为了防止出现后端返回结果不规范,处理有可能出现拼接出两个 反斜杠
  34. currentRouter.path = currentRouter.path.replace('//', '/');
  35. // 重定向
  36. item.redirect && (currentRouter.redirect = item.redirect);
  37. // 是否有子菜单,并递归处理
  38. if (item.children && item.children.length > 0) {
  39. //如果未定义 redirect 默认第一个子路由为 redirect
  40. !item.redirect && (currentRouter.redirect = `${item.path}/${item.children[0].path}`);
  41. // Recursion
  42. currentRouter.children = routerGenerator(item.children, currentRouter);
  43. }
  44. return currentRouter;
  45. });
  46. };
  47. /**
  48. * 动态生成菜单
  49. * @returns {Promise<Router>}
  50. */
  51. export const generatorDynamicRouter = (): Promise<RouteRecordRaw[]> => {
  52. return new Promise((resolve, reject) => {
  53. adminMenus()
  54. .then((result) => {
  55. const routeList = routerGenerator(result);
  56. asyncImportRoute(routeList);
  57. resolve(routeList);
  58. })
  59. .catch((err) => {
  60. reject(err);
  61. });
  62. });
  63. };
  64. /**
  65. * 查找views中对应的组件文件
  66. * */
  67. let viewsModules: Record<string, () => Promise<Recordable>>;
  68. export const asyncImportRoute = (routes: AppRouteRecordRaw[] | undefined): void => {
  69. viewsModules = viewsModules || import.meta.glob('../views/**/*.{vue,tsx}');
  70. if (!routes) return;
  71. routes.forEach((item) => {
  72. if (!item.component && item.meta?.frameSrc) {
  73. item.component = 'IFRAME';
  74. }
  75. const { component, name } = item;
  76. const { children } = item;
  77. if (component) {
  78. const layoutFound = LayoutMap.get(component as string);
  79. if (layoutFound) {
  80. item.component = layoutFound;
  81. } else {
  82. item.component = dynamicImport(viewsModules, component as string);
  83. }
  84. } else if (name) {
  85. item.component = ParentLayout;
  86. }
  87. children && asyncImportRoute(children);
  88. });
  89. };
  90. /**
  91. * 动态导入
  92. * */
  93. export const dynamicImport = (
  94. viewsModules: Record<string, () => Promise<Recordable>>,
  95. component: string
  96. ) => {
  97. const keys = Object.keys(viewsModules);
  98. const matchKeys = keys.filter((key) => {
  99. let k = key.replace('../views', '');
  100. const lastIndex = k.lastIndexOf('.');
  101. k = k.substring(0, lastIndex);
  102. return k === component;
  103. });
  104. if (matchKeys?.length === 1) {
  105. const matchKey = matchKeys[0];
  106. return viewsModules[matchKey];
  107. }
  108. if (matchKeys?.length > 1) {
  109. console.warn(
  110. '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'
  111. );
  112. return;
  113. }
  114. };