menuHelper.ts
2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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
66
67
68
69
70
71
72
import { AppRouteModule } from '/@/router/types';
import type { MenuModule, Menu, AppRouteRecordRaw } from '/@/router/types';
import { findPath, treeMap } from '/@/utils/helper/treeHelper';
import { cloneDeep } from 'lodash-es';
import { isUrl } from '/@/utils/is';
export function getAllParentPath<T = Recordable>(treeData: T[], path: string) {
const menuList = findPath(treeData, (n) => n.path === path) as Menu[];
return (menuList || []).map((item) => item.path);
}
function isPlainPath(path: string) {
return path.indexOf(':') === -1;
}
function joinParentPath(menus: Menu[], parentPath = '') {
for (let index = 0; index < menus.length; index++) {
const menu = menus[index];
// https://next.router.vuejs.org/guide/essentials/nested-routes.html
// Note that nested paths that start with / will be treated as a root path.
// This allows you to leverage the component nesting without having to use a nested URL.
if (!(menu.path.startsWith('/') || isUrl(menu.path))) {
// path doesn't start with /, nor is it a url, join parent path
menu.path = `${parentPath}/${menu.path}`;
}
if (menu?.children?.length) {
joinParentPath(menu.children, isPlainPath(menu.path) ? menu.path : parentPath);
}
}
}
// Parsing the menu module
export function transformMenuModule(menuModule: MenuModule): Menu {
const { menu } = menuModule;
const menuList = [menu];
joinParentPath(menuList);
return menuList[0];
}
export function transformRouteToMenu(routeModList: AppRouteModule[], routerMapping = false) {
const cloneRouteModList = cloneDeep(routeModList);
const routeList: AppRouteRecordRaw[] = [];
cloneRouteModList.forEach((item) => {
if (routerMapping && item.meta.hideChildrenInMenu && typeof item.redirect === 'string') {
item.path = item.redirect;
}
if (item.meta?.single) {
const realItem = item?.children?.[0];
realItem && routeList.push(realItem);
} else {
routeList.push(item);
}
});
const list = treeMap(routeList, {
conversion: (node: AppRouteRecordRaw) => {
const { meta: { title, hideMenu = false } = {} } = node;
return {
...(node.meta || {}),
meta: node.meta,
name: title,
hideMenu,
path: node.path,
};
},
});
joinParentPath(list);
return cloneDeep(list);
}