menuHelper.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. // https://next.router.vuejs.org/guide/essentials/nested-routes.html
  14. // Note that nested paths that start with / will be treated as a root path.
  15. // This allows you to leverage the component nesting without having to use a nested URL.
  16. if (!(menu.path.startsWith('/') || isUrl(menu.path))) {
  17. // path doesn't start with /, nor is it a url, join parent path
  18. menu.path = `${parentPath}/${menu.path}`;
  19. }
  20. if (menu?.children?.length) {
  21. joinParentPath(menu.children, menu.meta?.hidePathForChildren ? parentPath : menu.path);
  22. }
  23. }
  24. }
  25. // Parsing the menu module
  26. export function transformMenuModule(menuModule: MenuModule): Menu {
  27. const { menu } = menuModule;
  28. const menuList = [menu];
  29. joinParentPath(menuList);
  30. return menuList[0];
  31. }
  32. export function transformRouteToMenu(routeModList: AppRouteModule[], routerMapping = false) {
  33. const cloneRouteModList = cloneDeep(routeModList);
  34. const routeList: AppRouteRecordRaw[] = [];
  35. cloneRouteModList.forEach((item) => {
  36. if (routerMapping && item.meta.hideChildrenInMenu && typeof item.redirect === 'string') {
  37. item.path = item.redirect;
  38. }
  39. if (item.meta?.single) {
  40. const realItem = item?.children?.[0];
  41. realItem && routeList.push(realItem);
  42. } else {
  43. routeList.push(item);
  44. }
  45. });
  46. const list = treeMap(routeList, {
  47. conversion: (node: AppRouteRecordRaw) => {
  48. const { meta: { title, hideMenu = false } = {} } = node;
  49. return {
  50. ...(node.meta || {}),
  51. meta: node.meta,
  52. name: title,
  53. hideMenu,
  54. path: node.path,
  55. };
  56. },
  57. });
  58. joinParentPath(list);
  59. return cloneDeep(list);
  60. }