router-menu.md 8.19 KB

路由和菜单

本文将介绍 Venus Admin 中的路由配置和菜单管理。

路由配置

Venus Admin 使用 Vue Router 4 进行路由管理,支持动态路由和权限控制。

基础路由配置

在 src/router/routes/modules/ 目录下创建路由模块:

import type { RouteRecordRaw } from 'vue-router';

const routes: RouteRecordRaw[] = [
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: () => import('@/layouts/basic.vue'),
    redirect: '/dashboard/analysis',
    meta: {
      title: '仪表盘',
      icon: 'lucide:layout-dashboard',
      order: 0,
    },
    children: [
      {
        path: 'analysis',
        name: 'DashboardAnalysis',
        component: () => import('@/views/dashboard/analysis/index.vue'),
        meta: {
          title: '分析页',
          icon: 'lucide:area-chart',
        },
      },
      {
        path: 'workbench',
        name: 'DashboardWorkbench',
        component: () => import('@/views/dashboard/workbench/index.vue'),
        meta: {
          title: '工作台',
          icon: 'lucide:briefcase',
        },
      },
    ],
  },
];

export default routes;

路由 Meta 配置

路由的 meta 字段用于配置路由的额外信息:

interface RouteMeta {
  // 路由标题
  title: string;

  // 图标(支持 iconify)
  icon?: string;

  // 排序
  order?: number;

  // 是否隐藏在菜单中
  hideInMenu?: boolean;

  // 是否隐藏子菜单
  hideChildrenInMenu?: boolean;

  // 是否隐藏在面包屑中
  hideInBreadcrumb?: boolean;

  // 是否隐藏在标签页中
  hideInTabs?: boolean;

  // 是否固定在标签页中
  affixTab?: boolean;

  // 当前激活的菜单
  activeMenu?: string;

  // 权限码
  authority?: string[];

  // 是否缓存
  keepAlive?: boolean;

  // 外部链接
  link?: string;

  // 是否为全屏页面
  isFullscreen?: boolean;

  // 是否忽略权限
  ignoreAccess?: boolean;
}

动态路由

系统支持根据用户权限动态加载路由:

// src/router/guard/permission.ts
import { useAuthStore } from '@/store/modules/auth';

router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore();

  // 如果未加载动态路由
  if (!authStore.isDynamicRouteAdded) {
    // 获取用户权限路由
    const routes = await authStore.fetchUserRoutes();

    // 动态添加路由
    routes.forEach(route => {
      router.addRoute(route);
    });

    authStore.setDynamicRouteAdded(true);

    // 重定向到目标路由
    next({ ...to, replace: true });
  } else {
    next();
  }
});

菜单配置

自动生成菜单

菜单会根据路由配置自动生成,只需在路由的 meta 中配置相关信息:

{
  path: '/system',
  meta: {
    title: '系统管理',
    icon: 'lucide:settings',
    order: 999,
  },
  children: [
    {
      path: 'user',
      meta: {
        title: '用户管理',
        icon: 'lucide:users',
        authority: ['system:user:view'],
      },
    },
    {
      path: 'role',
      meta: {
        title: '角色管理',
        icon: 'lucide:shield',
        authority: ['system:role:view'],
      },
    },
  ],
}

隐藏菜单

某些路由不需要在菜单中显示,可以设置 hideInMenu:

{
  path: 'detail/:id',
  name: 'UserDetail',
  meta: {
    title: '用户详情',
    hideInMenu: true, // 不在菜单中显示
    activeMenu: '/system/user', // 激活父菜单
  },
}

外部链接

菜单可以配置为外部链接:

{
  path: 'https://github.com/venusjs/vue-venus-admin',
  meta: {
    title: 'GitHub',
    icon: 'lucide:github',
    link: 'https://github.com/venusjs/vue-venus-admin',
  },
}

菜单排序

通过 order 字段控制菜单的显示顺序(数值越小越靠前):

{
  path: '/dashboard',
  meta: {
    title: '仪表盘',
    order: 0, // 最前面
  },
}

{
  path: '/system',
  meta: {
    title: '系统管理',
    order: 999, // 最后面
  },
}

路由守卫

权限守卫

// src/router/guard/permission.ts
import { useAuthStore } from '@/store/modules/auth';

export function createPermissionGuard(router: Router) {
  router.beforeEach(async (to, from, next) => {
    const authStore = useAuthStore();

    // 白名单路由,直接放行
    if (to.meta.ignoreAccess) {
      next();
      return;
    }

    // 检查是否登录
    if (!authStore.isLoggedIn) {
      next({ name: 'Login', query: { redirect: to.fullPath } });
      return;
    }

    // 检查权限
    if (to.meta.authority) {
      const hasPermission = authStore.hasAuthority(to.meta.authority);
      if (!hasPermission) {
        next({ name: '403' });
        return;
      }
    }

    next();
  });
}

标题守卫

// src/router/guard/title.ts
export function createTitleGuard(router: Router) {
  router.afterEach((to) => {
    const title = to.meta.title;
    if (title) {
      document.title = `${title} - Venus Admin`;
    }
  });
}

进度条守卫

// src/router/guard/progress.ts
import NProgress from 'nprogress';

export function createProgressGuard(router: Router) {
  router.beforeEach(() => {
    NProgress.start();
  });

  router.afterEach(() => {
    NProgress.done();
  });
}

面包屑

面包屑会根据路由自动生成:

<template>
  <Breadcrumb :items="breadcrumbs" />
</template>

<script setup lang="ts">
import { computed } from 'vue';
import { useRoute } from 'vue-router';

const route = useRoute();

const breadcrumbs = computed(() => {
  return route.matched
    .filter(item => !item.meta.hideInBreadcrumb)
    .map(item => ({
      title: item.meta.title,
      path: item.path,
    }));
});
</script>

标签页

标签页配置

在 src/preferences.ts 中配置标签页:

export const overridesPreferences = defineOverridesPreferences({
  tabbar: {
    enable: true,      // 启用标签页
    persist: true,     // 持久化标签页
    height: 40,        // 标签页高度
  },
});

固定标签页

可以将某些页面固定在标签页中:

{
  path: '/dashboard',
  meta: {
    title: '仪表盘',
    affixTab: true, // 固定在标签页
  },
}

路由跳转

编程式导航

import { useRouter } from 'vue-router';

const router = useRouter();

// 跳转到指定路由
router.push('/dashboard');

// 带参数跳转
router.push({
  name: 'UserDetail',
  params: { id: '123' },
});

// 带查询参数跳转
router.push({
  path: '/user',
  query: { name: 'venus' },
});

// 替换当前路由
router.replace('/dashboard');

// 返回上一页
router.back();

// 前进到下一页
router.forward();

声明式导航

<template>
  <!-- 基础用法 -->
  <router-link to="/dashboard">仪表盘</router-link>

  <!-- 命名路由 -->
  <router-link :to="{ name: 'Dashboard' }">仪表盘</router-link>

  <!-- 带参数 -->
  <router-link :to="{ name: 'UserDetail', params: { id: '123' } }">
    用户详情
  </router-link>

  <!-- 带查询参数 -->
  <router-link :to="{ path: '/user', query: { name: 'venus' } }">
    用户列表
  </router-link>
</template>

路由工具函数

// src/router/utils.ts

// 获取所有菜单路由
export function getMenuRoutes(routes: RouteRecordRaw[]) {
  return routes.filter(route => !route.meta?.hideInMenu);
}

// 查找路由
export function findRoute(routes: RouteRecordRaw[], path: string) {
  for (const route of routes) {
    if (route.path === path) {
      return route;
    }
    if (route.children) {
      const found = findRoute(route.children, path);
      if (found) return found;
    }
  }
  return null;
}

// 扁平化路由
export function flatRoutes(routes: RouteRecordRaw[]): RouteRecordRaw[] {
  return routes.reduce((acc, route) => {
    acc.push(route);
    if (route.children) {
      acc.push(...flatRoutes(route.children));
    }
    return acc;
  }, [] as RouteRecordRaw[]);
}

下一步