menuHelper.ts 1.9 KB
Newer Older
V
vben 已提交
1
import { AppRouteModule } from '/@/router/types.d';
陈文彬 已提交
2 3
import type { MenuModule, Menu, AppRouteRecordRaw } from '/@/router/types';

V
vben 已提交
4
import { findPath, forEach, treeMap, treeToList } from '/@/utils/helper/treeHelper';
陈文彬 已提交
5 6 7 8 9 10 11 12 13 14 15
import { cloneDeep } from 'lodash-es';

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);
}

V
vben 已提交
16
// 拼接父级路径
陈文彬 已提交
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
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;
}

V
vben 已提交
36
// 解析菜单模块
陈文彬 已提交
37 38 39 40 41 42 43 44 45 46 47 48 49 50
export function transformMenuModule(menuModule: MenuModule): Menu {
  const { menu } = menuModule;

  const menuList = [menu];
  forEach(menuList, (m) => {
    joinParentPath(menuList, m);
  });
  return menuList[0];
}

export function transformRouteToMenu(routeModList: AppRouteModule[]) {
  const cloneRouteModList = cloneDeep(routeModList);
  const routeList: AppRouteRecordRaw[] = [];
  cloneRouteModList.forEach((item) => {
V
vben 已提交
51 52 53
    if (item.meta?.single) {
      const realItem = item?.children?.[0];
      realItem && routeList.push(realItem);
54
    } else {
V
vben 已提交
55
      routeList.push(item);
56
    }
陈文彬 已提交
57 58 59 60 61 62 63 64 65 66 67 68 69
  });
  return treeMap(routeList, {
    conversion: (node: AppRouteRecordRaw) => {
      const { meta: { title, icon } = {} } = node;
      joinParentPath(routeList, node);
      return {
        name: title,
        icon,
        path: node.path,
      };
    },
  });
}