Blame view

src/router/helper/menuHelper.ts 2.04 KB
1
import { AppRouteModule } from '/@/router/types';
陈文彬 authored
2
3
import type { MenuModule, Menu, AppRouteRecordRaw } from '/@/router/types';
4
import { findPath, treeMap } from '/@/utils/helper/treeHelper';
陈文彬 authored
5
import { cloneDeep } from 'lodash-es';
6
import { isUrl } from '/@/utils/is';
陈文彬 authored
7
8
export function getAllParentPath<T = Recordable>(treeData: T[], path: string) {
陈文彬 authored
9
10
11
12
  const menuList = findPath(treeData, (n) => n.path === path) as Menu[];
  return (menuList || []).map((item) => item.path);
}
13
14
15
function joinParentPath(menus: Menu[], parentPath = '') {
  for (let index = 0; index < menus.length; index++) {
    const menu = menus[index];
16
17
18
19
20
21
22
    // https://next.router.vuejs.org/guide/essentials/nested-routes.html
    // Note that nested paths that start with / will be treated as a root path.
    // This allows you to leverage the component nesting without having to use a nested URL.
    if (!(menu.path.startsWith('/') || isUrl(menu.path))) {
      // path doesn't start with /, nor is it a url, join parent path
      menu.path = `${parentPath}/${menu.path}`;
    }
23
    if (menu?.children?.length) {
24
      joinParentPath(menu.children, menu.path);
25
    }
陈文彬 authored
26
27
28
  }
}
29
// Parsing the menu module
陈文彬 authored
30
31
32
33
export function transformMenuModule(menuModule: MenuModule): Menu {
  const { menu } = menuModule;

  const menuList = [menu];
vben authored
34
35
  joinParentPath(menuList);
陈文彬 authored
36
37
38
39
40
41
  return menuList[0];
}

export function transformRouteToMenu(routeModList: AppRouteModule[]) {
  const cloneRouteModList = cloneDeep(routeModList);
  const routeList: AppRouteRecordRaw[] = [];
42
陈文彬 authored
43
  cloneRouteModList.forEach((item) => {
vben authored
44
45
46
    if (item.meta?.single) {
      const realItem = item?.children?.[0];
      realItem && routeList.push(realItem);
47
    } else {
vben authored
48
      routeList.push(item);
49
    }
陈文彬 authored
50
  });
51
  const list = treeMap(routeList, {
陈文彬 authored
52
    conversion: (node: AppRouteRecordRaw) => {
53
      const { meta: { title, hideMenu = false } = {} } = node;
54
陈文彬 authored
55
      return {
56
        ...(node.meta || {}),
57
        meta: node.meta,
陈文彬 authored
58
        name: title,
59
        hideMenu,
60
        path: node.path,
陈文彬 authored
61
62
63
      };
    },
  });
64
  joinParentPath(list);
65
  return cloneDeep(list);
陈文彬 authored
66
}