MENU_DOCS.md 12.6 KB

多级路由菜单系统说明文档

概述

本系统实现了一个支持二级和三级子菜单的路由菜单系统,适用于微前端架构的主应用。菜单系统具有以下特点:

  • ✅ 支持最多三级菜单嵌套
  • ✅ 自动展开/收起子菜单
  • ✅ 路由激活状态自动高亮
  • ✅ 自动生成面包屑导航
  • ✅ 支持菜单图标、徽章、权限控制
  • ✅ 响应式设计,流畅的展开/收起动画
  • ✅ 与 Vue Router 深度集成

文件结构

apps/frontend-micro/scrm-base/src/
├── types/
│   └── menu.ts                    # 菜单类型定义
├── config/
│   └── menus.ts                   # 菜单配置文件
├── components/
│   └── SidebarMenuItem.vue        # 侧边栏菜单项组件(递归)
├── layouts/
│   └── BasicLayout.vue            # 基础布局(包含菜单渲染逻辑)
└── router/
    └── index.ts                   # 路由配置

数据结构

1. MenuItem 接口

菜单项的核心数据结构,支持递归嵌套。

interface MenuItem {
  /** 菜单唯一标识 */
  id: string;

  /** 菜单标题 */
  title: string;

  /** 路由路径 */
  path: string;

  /** 菜单图标(emoji 或图标类名) */
  icon?: string;

  /** 子菜单列表(支持递归) */
  children?: MenuItem[];

  /** 是否隐藏菜单项 */
  hidden?: boolean;

  /** 菜单层级(1-一级,2-二级,3-三级) */
  level?: number;

  /** 父级菜单ID */
  parentId?: string;

  /** 扩展元数据 */
  meta?: {
    requireAuth?: boolean;      // 是否需要权限
    permission?: string;         // 权限标识
    order?: number;              // 排序权重
    externalLink?: string;       // 外部链接
    showInBreadcrumb?: boolean;  // 是否在面包屑中显示
    keepAlive?: boolean;         // 是否缓存页面
    badge?: number | string;     // 徽章数字
  };
}

2. TopMenuItem 接口

顶部导航菜单项,关联不同的侧边栏菜单。

interface TopMenuItem {
  /** 菜单唯一标识 */
  id: string;

  /** 菜单标题 */
  title: string;

  /** 路由路径 */
  path: string;

  /** 菜单图标 */
  icon?: string;

  /** 对应的侧边栏菜单 */
  sidebarMenus?: MenuItem[];
}

3. BreadcrumbItem 接口

面包屑导航项。

interface BreadcrumbItem {
  /** 标题 */
  title: string;

  /** 路径(可选,用于点击跳转) */
  path?: string;
}

菜单配置示例

示例 1:一级菜单(无子菜单)

const homeMenus: MenuItem[] = [
  {
    id: 'dashboard',
    title: '工作台',
    path: '/home/dashboard',
    icon: '📊',
    level: 1,
  },
  {
    id: 'analytics',
    title: '数据概览',
    path: '/home/analytics',
    icon: '📈',
    level: 1,
  },
];

示例 2:二级菜单

const vueAppMenus: MenuItem[] = [
  {
    id: 'customer',
    title: '客户管理',
    path: '/subapp-vue/customer',
    icon: '👥',
    level: 1,
    children: [
      {
        id: 'customer-list',
        title: '客户列表',
        path: '/subapp-vue/customer/list',
        icon: '📋',
        level: 2,
        parentId: 'customer',
      },
      {
        id: 'customer-tags',
        title: '客户标签',
        path: '/subapp-vue/customer/tags',
        icon: '🏷️',
        level: 2,
        parentId: 'customer',
      },
    ],
  },
];

示例 3:三级菜单

const vueAppMenus: MenuItem[] = [
  {
    id: 'marketing',
    title: '营销活动',
    path: '/subapp-vue/marketing',
    icon: '🎯',
    level: 1,
    children: [
      {
        id: 'marketing-campaign',
        title: '活动管理',
        path: '/subapp-vue/marketing/campaign',
        icon: '📢',
        level: 2,
        parentId: 'marketing',
        children: [
          {
            id: 'marketing-campaign-list',
            title: '活动列表',
            path: '/subapp-vue/marketing/campaign/list',
            icon: '📃',
            level: 3,
            parentId: 'marketing-campaign',
          },
          {
            id: 'marketing-campaign-create',
            title: '创建活动',
            path: '/subapp-vue/marketing/campaign/create',
            icon: '➕',
            level: 3,
            parentId: 'marketing-campaign',
          },
        ],
      },
    ],
  },
];

示例 4:带徽章的菜单

{
  id: 'notifications',
  title: '通知中心',
  path: '/notifications',
  icon: '🔔',
  level: 1,
  meta: {
    badge: 5,  // 显示未读数量
  },
}

核心功能说明

1. 自动展开/收起

  • 点击有子菜单的菜单项时,自动展开/收起
  • 路由变化时,自动展开当前激活路由的所有父级菜单
  • 使用 expandedKeys Set 管理展开状态
// 监听路由变化,自动展开
watch(() => route.path, (newPath) => {
  const paths = getMenuParentPaths(currentSidebarMenus.value, newPath);

  function expandParents(menus: MenuItem[], targetPath: string) {
    for (const menu of menus) {
      if (menu.children) {
        const hasActiveChild = paths.includes(menu.path);
        if (hasActiveChild) {
          expandedKeys.value.add(menu.id);
          expandParents(menu.children, targetPath);
        }
      }
    }
  }

  expandParents(currentSidebarMenus.value, newPath);
}, { immediate: true });

2. 路由激活高亮

  • 当前路由完全匹配时高亮
  • 当前路由是子路由时,父级菜单也高亮
  • 使用路径前缀匹配算法
const isActive = computed(() => {
  return props.activePath === props.menu.path || 
         props.activePath.startsWith(props.menu.path + '/');
});

3. 面包屑导航

  • 根据当前路由自动生成面包屑
  • 支持点击面包屑项快速导航
  • 最后一项不可点击
const breadcrumbs = computed<BreadcrumbItem[]>(() => {
  const crumbs: BreadcrumbItem[] = [{ title: '首页', path: '/home' }];

  const paths = getMenuParentPaths(currentSidebarMenus.value, route.path);

  paths.forEach(path => {
    const menu = findMenuByPath(currentSidebarMenus.value, path);
    if (menu) {
      crumbs.push({ title: menu.title, path: menu.path });
    }
  });

  return crumbs;
});

4. 递归菜单组件

SidebarMenuItem.vue 是一个递归组件,通过自身调用实现多级嵌套。

<template>
  <div class="sidebar-menu-item">
    <div class="menu-item-content" @click="handleClick">
      <!-- 菜单内容 -->
    </div>

    <!-- 递归渲染子菜单 -->
    <transition name="submenu-expand">
      <div v-if="hasChildren && isExpanded" class="submenu">
        <SidebarMenuItem
          v-for="child in menu.children"
          :key="child.id"
          :menu="child"
          @click="$emit('click', $event)"
          @toggle="$emit('toggle', $event)"
        />
      </div>
    </transition>
  </div>
</template>

工具函数

1. getSidebarMenusByPath

根据当前路由路径获取对应的侧边栏菜单。

export function getSidebarMenusByPath(path: string): MenuItem[] {
  const topMenu = topMenus.find(menu => path.startsWith(menu.path));
  return topMenu?.sidebarMenus || [];
}

2. findMenuItem

递归查找指定 ID 的菜单项。

export function findMenuItem(menus: MenuItem[], id: string): MenuItem | null {
  for (const menu of menus) {
    if (menu.id === id) return menu;
    if (menu.children) {
      const found = findMenuItem(menu.children, id);
      if (found) return found;
    }
  }
  return null;
}

3. getMenuParentPaths

获取从根菜单到目标路径的所有父级路径。

export function getMenuParentPaths(menus: MenuItem[], targetPath: string): string[] {
  const paths: string[] = [];

  function findPath(items: MenuItem[], target: string, currentPaths: string[]): boolean {
    for (const item of items) {
      const newPaths = [...currentPaths, item.path];

      if (item.path === target) {
        paths.push(...newPaths);
        return true;
      }

      if (item.children && findPath(item.children, target, newPaths)) {
        return true;
      }
    }
    return false;
  }

  findPath(menus, targetPath, []);
  return paths;
}

样式说明

层级缩进

不同层级的菜单通过 padding-left 实现视觉层级:

.menu-item-content.level-1 {
  padding-left: 16px;
}

.menu-item-content.level-2 {
  padding-left: 32px;
  font-size: 13px;
}

.menu-item-content.level-3 {
  padding-left: 48px;
  font-size: 12px;
}

展开动画

子菜单的展开/收起使用 Vue Transition:

.submenu-expand-enter-active,
.submenu-expand-leave-active {
  transition: all 0.3s ease;
}

.submenu-expand-enter-from,
.submenu-expand-leave-to {
  opacity: 0;
  max-height: 0;
  transform: translateY(-10px);
}

.submenu-expand-enter-to,
.submenu-expand-leave-from {
  opacity: 1;
  max-height: 1000px;
  transform: translateY(0);
}

激活状态

激活的菜单项有左侧蓝色边框:

.menu-item-content.active::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 3px;
  background-color: #1890ff;
}

使用指南

1. 添加新菜单

在 config/menus.ts 中添加菜单配置:

export const myNewMenus: MenuItem[] = [
  {
    id: 'new-module',
    title: '新模块',
    path: '/new-module',
    icon: '🆕',
    level: 1,
    children: [
      {
        id: 'new-module-sub',
        title: '子功能',
        path: '/new-module/sub',
        icon: '📦',
        level: 2,
        parentId: 'new-module',
      },
    ],
  },
];

// 添加到顶部菜单
export const topMenus: TopMenuItem[] = [
  // ... 其他菜单
  {
    id: 'new-module',
    title: '新模块',
    path: '/new-module',
    icon: '🆕',
    sidebarMenus: myNewMenus,
  },
];

2. 配置路由

在 router/index.ts 中添加对应的路由:

{
  path: '/new-module',
  name: 'NewModule',
  component: () => import('@/views/NewModule.vue'),
  meta: {
    title: '新模块',
    level: 1,
  },
  children: [
    {
      path: 'sub',
      name: 'NewModuleSub',
      component: () => import('@/views/NewModuleSub.vue'),
      meta: {
        title: '子功能',
        level: 2,
      },
    },
  ],
}

3. 权限控制

通过 meta.permission 字段控制权限:

{
  id: 'admin',
  title: '系统管理',
  path: '/admin',
  icon: '⚙️',
  level: 1,
  meta: {
    requireAuth: true,
    permission: 'admin',
  },
}

在路由守卫中检查权限:

router.beforeEach((to, from, next) => {
  if (to.meta.requireAuth) {
    // 检查用户权限
    const hasPermission = checkPermission(to.meta.permission);
    if (!hasPermission) {
      next('/403');
      return;
    }
  }
  next();
});

最佳实践

1. 菜单命名规范

  • ID 使用 kebab-case:customer-management
  • 路径与 ID 保持一致:/customer/management
  • 子菜单 ID 使用父级前缀:customer-management-list

2. 层级限制

  • 建议最多使用三级菜单
  • 超过三级会导致用户体验下降
  • 如果业务复杂,考虑拆分模块

3. 图标使用

  • 优先使用 emoji,兼容性好
  • 可以使用图标库(如 Ant Design Icons)
  • 保持图标风格统一

4. 性能优化

  • 路由组件使用懒加载
  • 大型菜单考虑虚拟滚动
  • 避免菜单数据过于庞大

常见问题

Q1: 如何动态加载菜单?

// 从后端获取菜单数据
const loadMenus = async () => {
  const response = await fetch('/api/menus');
  const data = await response.json();
  currentSidebarMenus.value = data;
};

Q2: 如何隐藏某些菜单项?

{
  id: 'hidden-menu',
  title: '隐藏菜单',
  path: '/hidden',
  icon: '🔒',
  hidden: true,  // 设置为 true
}

在渲染时过滤:

<template v-for="item in currentSidebarMenus.filter(m => !m.hidden)">
  <!-- 渲染菜单 -->
</template>

Q3: 如何实现菜单搜索?

const searchMenus = (keyword: string, menus: MenuItem[]): MenuItem[] => {
  const results: MenuItem[] = [];

  for (const menu of menus) {
    if (menu.title.includes(keyword)) {
      results.push(menu);
    }
    if (menu.children) {
      results.push(...searchMenus(keyword, menu.children));
    }
  }

  return results;
};

总结

本多级路由菜单系统提供了完整的菜单管理方案,具有良好的扩展性和可维护性。通过合理配置菜单数据和路由,可以快速构建复杂的导航结构。

如有问题或建议,欢迎反馈! 🎉