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

72 lines
2.0 KiB
TypeScript
Raw Normal View History

2020-12-03 21:49:32 +08:00
import { AppRouteModule } from '/@/router/types.d';
2020-09-28 20:19:10 +08:00
import type { MenuModule, Menu, AppRouteRecordRaw } from '/@/router/types';
2020-12-03 21:49:32 +08:00
import { findPath, forEach, treeMap, treeToList } 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(treeData: any[], path: string) {
const menuList = findPath(treeData, (n) => n.path === path) as Menu[];
return (menuList || []).map((item) => item.path);
}
export function flatMenus(menus: Menu[]) {
return treeToList(menus);
}
2020-10-14 21:08:07 +08:00
// 拼接父级路径
2020-09-28 20:19:10 +08:00
function joinParentPath(list: any, node: any) {
let allPaths = getAllParentPath(list, node.path);
allPaths = allPaths.slice(0, allPaths.length - 1);
let parentPath = '';
if (Array.isArray(allPaths) && allPaths.length >= 2) {
parentPath = allPaths[allPaths.length - 1];
} else {
allPaths.forEach((p) => {
parentPath += /^\//.test(p) ? p : `/${p}`;
});
}
node.path = `${parentPath}${/^\//.test(node.path) ? node.path : `/${node.path}`}`.replace(
/\/\//g,
'/'
);
return node;
}
2020-10-14 21:08:07 +08:00
// 解析菜单模块
2020-09-28 20:19:10 +08:00
export function transformMenuModule(menuModule: MenuModule): Menu {
const { menu } = menuModule;
const menuList = [menu];
forEach(menuList, (m) => {
2020-12-07 23:56:57 +08:00
!isUrl(m.path) && joinParentPath(menuList, m);
2020-09-28 20:19:10 +08:00
});
return menuList[0];
}
export function transformRouteToMenu(routeModList: AppRouteModule[]) {
const cloneRouteModList = cloneDeep(routeModList);
const routeList: AppRouteRecordRaw[] = [];
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
});
return treeMap(routeList, {
conversion: (node: AppRouteRecordRaw) => {
const { meta: { title, icon } = {} } = node;
2020-12-07 23:56:57 +08:00
!isUrl(node.path) && joinParentPath(routeList, node);
2020-09-28 20:19:10 +08:00
return {
name: title,
icon,
path: node.path,
};
},
});
}