vben
authored
5 years ago
1
2
3
4
5
6
7
import type { AppRouteModule, AppRouteRecordRaw } from '/@/router/types';
import type { RouteLocationNormalized, RouteRecordNormalized } from 'vue-router';
import { getParentLayout, LAYOUT } from '/@/router/constant';
import dynamicImport from './dynamicImport';
import { cloneDeep } from 'lodash-es';
vben
authored
5 years ago
8
9
10
11
export type LayoutMapKey = 'LAYOUT';
const LayoutMap = new Map<LayoutMapKey, () => Promise<typeof import('*.vue')>>();
vben
authored
5 years ago
12
13
14
15
16
17
18
// 动态引入
function asyncImportRoute(routes: AppRouteRecordRaw[] | undefined) {
if (!routes) return;
routes.forEach((item) => {
const { component, name } = item;
const { children } = item;
if (component) {
vben
authored
5 years ago
19
item.component = dynamicImport(component as string);
vben
authored
5 years ago
20
21
22
23
24
25
26
27
28
} else if (name) {
item.component = getParentLayout(name);
}
children && asyncImportRoute(children);
});
}
// Turn background objects into routing objects
export function transformObjToRoute<T = AppRouteModule>(routeList: AppRouteModule[]): T[] {
vben
authored
5 years ago
29
30
LayoutMap.set('LAYOUT', LAYOUT);
vben
authored
5 years ago
31
32
33
routeList.forEach((route) => {
if (route.component) {
if ((route.component as string).toUpperCase() === 'LAYOUT') {
vben
authored
5 years ago
34
route.component = LayoutMap.get(route.component as LayoutMapKey);
vben
authored
5 years ago
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
} 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;
}
}
route.children && asyncImportRoute(route.children);
});
return (routeList as unknown) as T[];
}
// Return to the new routing structure, not affected by the original example
export function getRoute(route: RouteLocationNormalized): RouteLocationNormalized {
if (!route) return route;
const { matched, ...opt } = route;
return {
...opt,
matched: (matched
? matched.map((item) => ({
meta: item.meta,
name: item.name,
path: item.path,
}))
: undefined) as RouteRecordNormalized[],
};
}