menuHelper.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import { AppRouteModule } from '/@/router/types.d';
  2. import type { MenuModule, Menu, AppRouteRecordRaw } from '/@/router/types';
  3. import { findPath, forEach, treeMap, treeToList } from './treeHelper';
  4. import { cloneDeep } from 'lodash-es';
  5. export function getAllParentPath(treeData: any[], path: string) {
  6. const menuList = findPath(treeData, (n) => n.path === path) as Menu[];
  7. return (menuList || []).map((item) => item.path);
  8. }
  9. export function flatMenus(menus: Menu[]) {
  10. return treeToList(menus);
  11. }
  12. // 拼接父级路径
  13. function joinParentPath(list: any, node: any) {
  14. let allPaths = getAllParentPath(list, node.path);
  15. allPaths = allPaths.slice(0, allPaths.length - 1);
  16. let parentPath = '';
  17. if (Array.isArray(allPaths) && allPaths.length >= 2) {
  18. parentPath = allPaths[allPaths.length - 1];
  19. } else {
  20. allPaths.forEach((p) => {
  21. parentPath += /^\//.test(p) ? p : `/${p}`;
  22. });
  23. }
  24. node.path = `${parentPath}${/^\//.test(node.path) ? node.path : `/${node.path}`}`.replace(
  25. /\/\//g,
  26. '/'
  27. );
  28. return node;
  29. }
  30. // 解析菜单模块
  31. export function transformMenuModule(menuModule: MenuModule): Menu {
  32. const { menu } = menuModule;
  33. const menuList = [menu];
  34. forEach(menuList, (m) => {
  35. joinParentPath(menuList, m);
  36. });
  37. return menuList[0];
  38. }
  39. export function transformRouteToMenu(routeModList: AppRouteModule[]) {
  40. const cloneRouteModList = cloneDeep(routeModList);
  41. const routeList: AppRouteRecordRaw[] = [];
  42. cloneRouteModList.forEach((item) => {
  43. const { layout, routes, children } = item;
  44. if (layout) {
  45. layout.children = routes || children;
  46. routeList.push(layout);
  47. } else {
  48. routes && routeList.push(...routes);
  49. }
  50. });
  51. return treeMap(routeList, {
  52. conversion: (node: AppRouteRecordRaw) => {
  53. const { meta: { title, icon } = {} } = node;
  54. joinParentPath(routeList, node);
  55. return {
  56. name: title,
  57. icon,
  58. path: node.path,
  59. };
  60. },
  61. });
  62. }