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

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

export function getAllParentPath(treeData: any[], path: string) {
  const menuList = findPath(treeData, (n) => n.path === path) as Menu[];
  return (menuList || []).map((item) => item.path);
}

V
vben 已提交
13
// 拼接父级路径
陈文彬 已提交
14 15 16 17 18 19 20 21 22 23 24 25
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}`;
    });
  }
V
vben 已提交
26
  node.path = `${/^\//.test(node.path) ? node.path : `${parentPath}/${node.path}`}`.replace(
陈文彬 已提交
27 28 29 30 31 32
    /\/\//g,
    '/'
  );
  return node;
}

V
vben 已提交
33
// 解析菜单模块
陈文彬 已提交
34 35 36 37 38
export function transformMenuModule(menuModule: MenuModule): Menu {
  const { menu } = menuModule;

  const menuList = [menu];
  forEach(menuList, (m) => {
V
vben 已提交
39
    !isUrl(m.path) && joinParentPath(menuList, m);
陈文彬 已提交
40
  });
V
vben 已提交
41

陈文彬 已提交
42 43 44 45 46 47
  return menuList[0];
}

export function transformRouteToMenu(routeModList: AppRouteModule[]) {
  const cloneRouteModList = cloneDeep(routeModList);
  const routeList: AppRouteRecordRaw[] = [];
48 49 50 51 52 53 54

  // cloneRouteModList = filter(cloneRouteModList, (node) => {
  //   if (Reflect.has(node?.meta ?? {}, 'hideMenu')) {
  //     return !node?.meta.hideMenu;
  //   }
  //   return true;
  // });
陈文彬 已提交
55
  cloneRouteModList.forEach((item) => {
V
vben 已提交
56 57 58
    if (item.meta?.single) {
      const realItem = item?.children?.[0];
      realItem && routeList.push(realItem);
59
    } else {
V
vben 已提交
60
      routeList.push(item);
61
    }
陈文彬 已提交
62 63 64
  });
  return treeMap(routeList, {
    conversion: (node: AppRouteRecordRaw) => {
65
      const { meta: { title, icon, hideMenu = false } = {} } = node;
V
vben 已提交
66 67

      !isUrl(node.path) && joinParentPath(routeList, node);
陈文彬 已提交
68 69 70 71
      return {
        name: title,
        icon,
        path: node.path,
72
        hideMenu,
陈文彬 已提交
73 74 75 76
      };
    },
  });
}