menuHelper.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { AppRouteModule } from '/@/router/types';
  2. import type { MenuModule, Menu, AppRouteRecordRaw } from '/@/router/types';
  3. import { findPath, treeMap } from '/@/utils/helper/treeHelper';
  4. import { cloneDeep } from 'lodash-es';
  5. import { isUrl } from '/@/utils/is';
  6. export function getAllParentPath<T = Recordable>(treeData: T[], path: string) {
  7. const menuList = findPath(treeData, (n) => n.path === path) as Menu[];
  8. return (menuList || []).map((item) => item.path);
  9. }
  10. function joinParentPath(menus: Menu[], parentPath = '') {
  11. for (let index = 0; index < menus.length; index++) {
  12. const menu = menus[index];
  13. const p = menu.path.startsWith('/') ? menu.path : `/${menu.path}`;
  14. const parent = isUrl(menu.path) ? menu.path : `${parentPath}${p}`;
  15. menus[index].path = parent;
  16. if (menu?.children?.length) {
  17. joinParentPath(menu.children, parent);
  18. }
  19. }
  20. }
  21. // Parsing the menu module
  22. export function transformMenuModule(menuModule: MenuModule): Menu {
  23. const { menu } = menuModule;
  24. const menuList = [menu];
  25. joinParentPath(menuList);
  26. return menuList[0];
  27. }
  28. export function transformRouteToMenu(routeModList: AppRouteModule[]) {
  29. const cloneRouteModList = cloneDeep(routeModList);
  30. const routeList: AppRouteRecordRaw[] = [];
  31. cloneRouteModList.forEach((item) => {
  32. if (item.meta?.single) {
  33. const realItem = item?.children?.[0];
  34. realItem && routeList.push(realItem);
  35. } else {
  36. routeList.push(item);
  37. }
  38. });
  39. const list = treeMap(routeList, {
  40. conversion: (node: AppRouteRecordRaw) => {
  41. const { meta: { title, hideMenu = false } = {} } = node;
  42. return {
  43. ...(node.meta || {}),
  44. name: title,
  45. hideMenu,
  46. path: node.path,
  47. };
  48. },
  49. });
  50. joinParentPath(list);
  51. return cloneDeep(list);
  52. }