menuHelper.ts 1.9 KB

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