vue-vben-admin/src/router/helper/menuHelper.ts

62 lines
1.8 KiB
TypeScript
Raw Normal View History

import { AppRouteModule } from '/@/router/types';
2020-09-28 20:19:10 +08:00
import type { MenuModule, Menu, AppRouteRecordRaw } from '/@/router/types';
import { findPath, treeMap } from '/@/utils/helper/treeHelper';
2020-09-28 20:19:10 +08:00
import { cloneDeep } from 'lodash-es';
2020-12-07 23:56:57 +08:00
import { isUrl } from '/@/utils/is';
2020-09-28 20:19:10 +08:00
export function getAllParentPath<T = Recordable>(treeData: T[], path: string) {
2020-09-28 20:19:10 +08:00
const menuList = findPath(treeData, (n) => n.path === path) as Menu[];
return (menuList || []).map((item) => item.path);
}
function joinParentPath(menus: Menu[], parentPath = '') {
for (let index = 0; index < menus.length; index++) {
const menu = menus[index];
const p = menu.path.startsWith('/') ? menu.path : `/${menu.path}`;
const parent = isUrl(menu.path) ? menu.path : `${parentPath}${p}`;
menus[index].path = parent;
if (menu?.children?.length) {
joinParentPath(menu.children, parent);
}
2020-09-28 20:19:10 +08:00
}
}
// Parsing the menu module
2020-09-28 20:19:10 +08:00
export function transformMenuModule(menuModule: MenuModule): Menu {
const { menu } = menuModule;
const menuList = [menu];
2020-12-14 00:41:00 +08:00
joinParentPath(menuList);
2020-09-28 20:19:10 +08:00
return menuList[0];
}
export function transformRouteToMenu(routeModList: AppRouteModule[]) {
const cloneRouteModList = cloneDeep(routeModList);
const routeList: AppRouteRecordRaw[] = [];
2020-09-28 20:19:10 +08:00
cloneRouteModList.forEach((item) => {
2020-12-03 21:49:32 +08:00
if (item.meta?.single) {
const realItem = item?.children?.[0];
realItem && routeList.push(realItem);
} else {
2020-12-03 21:49:32 +08:00
routeList.push(item);
}
2020-09-28 20:19:10 +08:00
});
const list = treeMap(routeList, {
2020-09-28 20:19:10 +08:00
conversion: (node: AppRouteRecordRaw) => {
const { meta: { title, hideMenu = false } = {} } = node;
2020-09-28 20:19:10 +08:00
return {
...(node.meta || {}),
2020-09-28 20:19:10 +08:00
name: title,
hideMenu,
path: node.path,
2020-09-28 20:19:10 +08:00
};
},
});
joinParentPath(list);
return cloneDeep(list);
2020-09-28 20:19:10 +08:00
}