Blame view

src/router/helper/routeHelper.ts 6.01 KB
vben authored
1
import type { AppRouteModule, AppRouteRecordRaw } from '/@/router/types';
2
import type { Router, RouteRecordNormalized } from 'vue-router';
vben authored
3
4
import { getParentLayout, LAYOUT, EXCEPTION_COMPONENT } from '/@/router/constant';
5
import { cloneDeep, omit } from 'lodash-es';
vben authored
6
import { warn } from '/@/utils/log';
7
import { createRouter, createWebHashHistory } from 'vue-router';
vben authored
8
9
export type LayoutMapKey = 'LAYOUT';
10
const IFRAME = () => import('/@/views/sys/iframe/FrameBlank.vue');
11
12
const LayoutMap = new Map<string, () => Promise<typeof import('*.vue')>>();
13
14
15

LayoutMap.set('LAYOUT', LAYOUT);
LayoutMap.set('IFRAME', IFRAME);
16
17
let dynamicViewsModules: Record<string, () => Promise<Recordable>>;
18
19
// Dynamic introduction
vben authored
20
function asyncImportRoute(routes: AppRouteRecordRaw[] | undefined) {
Vben authored
21
  dynamicViewsModules = dynamicViewsModules || import.meta.glob('../../views/**/*.{vue,tsx}');
vben authored
22
23
  if (!routes) return;
  routes.forEach((item) => {
24
25
26
    if (!item.component && item.meta?.frameSrc) {
      item.component = 'IFRAME';
    }
vben authored
27
28
29
    const { component, name } = item;
    const { children } = item;
    if (component) {
30
      const layoutFound = LayoutMap.get(component.toUpperCase());
31
32
33
34
35
      if (layoutFound) {
        item.component = layoutFound;
      } else {
        item.component = dynamicImport(dynamicViewsModules, component as string);
      }
vben authored
36
    } else if (name) {
37
      item.component = getParentLayout();
vben authored
38
39
40
41
42
    }
    children && asyncImportRoute(children);
  });
}
43
function dynamicImport(
44
  dynamicViewsModules: Record<string, () => Promise<Recordable>>,
vben authored
45
  component: string,
46
47
) {
  const keys = Object.keys(dynamicViewsModules);
vben authored
48
  const matchKeys = keys.filter((key) => {
49
50
51
52
53
54
    const k = key.replace('../../views', '');
    const startFlag = component.startsWith('/');
    const endFlag = component.endsWith('.vue') || component.endsWith('.tsx');
    const startIndex = startFlag ? 0 : 1;
    const lastIndex = endFlag ? k.length : k.lastIndexOf('.');
    return k.substring(startIndex, lastIndex) === component;
vben authored
55
56
57
  });
  if (matchKeys?.length === 1) {
    const matchKey = matchKeys[0];
58
    return dynamicViewsModules[matchKey];
59
  } else if (matchKeys?.length > 1) {
vben authored
60
    warn(
vben authored
61
      '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',
vben authored
62
63
    );
    return;
64
  } else {
65
    warn('在src/views/下找不到`' + component + '.vue` 或 `' + component + '.tsx`, 请自行创建!');
66
    return EXCEPTION_COMPONENT;
vben authored
67
68
69
  }
}
vben authored
70
// Turn background objects into routing objects
71
// 将背景对象变成路由对象
vben authored
72
73
export function transformObjToRoute<T = AppRouteModule>(routeList: AppRouteModule[]): T[] {
  routeList.forEach((route) => {
74
75
76
77
    const component = route.component as string;
    if (component) {
      if (component.toUpperCase() === 'LAYOUT') {
        route.component = LayoutMap.get(component.toUpperCase());
vben authored
78
79
80
81
82
83
84
85
86
87
      } else {
        route.children = [cloneDeep(route)];
        route.component = LAYOUT;
        route.name = `${route.name}Parent`;
        route.path = '';
        const meta = route.meta || {};
        meta.single = true;
        meta.affix = false;
        route.meta = meta;
      }
88
89
    } else {
      warn('请正确配置路由:' + route?.name + '的component属性');
vben authored
90
91
92
    }
    route.children && asyncImportRoute(route.children);
  });
93
  return routeList as unknown as T[];
vben authored
94
95
}
96
97
/**
 * Convert multi-level routing to level 2 routing
98
 * 将多级路由转换为 2 级路由
99
 */
100
101
export function flatMultiLevelRoutes(routeModules: AppRouteModule[]) {
  const modules: AppRouteModule[] = cloneDeep(routeModules);
102
103
104
  for (let index = 0; index < modules.length; index++) {
    const routeModule = modules[index];
105
    // 判断级别是否 多级 路由
106
    if (!isMultipleRoute(routeModule)) {
107
      // 声明终止当前循环, 即跳过此次循环,进行下一轮
108
109
      continue;
    }
110
    // 路由等级提升
111
112
    promoteRouteLevel(routeModule);
  }
113
  return modules;
114
115
116
}

// Routing level upgrade
117
// 路由等级提升
118
119
function promoteRouteLevel(routeModule: AppRouteModule) {
  // Use vue-router to splice menus
120
121
  // 使用vue-router拼接菜单
  // createRouter 创建一个可以被 Vue 应用程序使用的路由实例
122
  let router: Router | null = createRouter({
123
    routes: [routeModule as unknown as RouteRecordNormalized],
124
125
    history: createWebHashHistory(),
  });
126
  // getRoutes: 获取所有 路由记录的完整列表。
127
  const routes = router.getRoutes();
128
  // 将所有子路由添加到二级路由
129
  addToChildren(routes, routeModule.children || [], routeModule);
130
131
  router = null;
132
  // omit lodash的函数 对传入的item对象的children进行删除
133
  routeModule.children = routeModule.children?.map((item) => omit(item, 'children'));
134
135
136
}

// Add all sub-routes to the secondary route
137
// 将所有子路由添加到二级路由
138
139
140
function addToChildren(
  routes: RouteRecordNormalized[],
  children: AppRouteRecordRaw[],
vben authored
141
  routeModule: AppRouteModule,
142
143
144
145
) {
  for (let index = 0; index < children.length; index++) {
    const child = children[index];
    const route = routes.find((item) => item.name === child.name);
146
147
148
149
150
    if (!route) {
      continue;
    }
    routeModule.children = routeModule.children || [];
    if (!routeModule.children.find((item) => item.name === route.name)) {
151
      routeModule.children?.push(route as unknown as AppRouteModule);
152
153
154
    }
    if (child.children?.length) {
      addToChildren(routes, child.children, routeModule);
155
156
157
158
159
    }
  }
}

// Determine whether the level exceeds 2 levels
160
// 判断级别是否超过2级
161
function isMultipleRoute(routeModule: AppRouteModule) {
162
  // Reflect.has 与 in 操作符 相同, 用于检查一个对象(包括它原型链上)是否拥有某个属性
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
  if (!routeModule || !Reflect.has(routeModule, 'children') || !routeModule.children?.length) {
    return false;
  }

  const children = routeModule.children;

  let flag = false;
  for (let index = 0; index < children.length; index++) {
    const child = children[index];
    if (child.children?.length) {
      flag = true;
      break;
    }
  }
  return flag;
vben authored
178
}