使用 Vue Router 动态生成路由和侧边栏导航

动态生成路由和侧边栏导航

在这个示例中,我们实现了一个动态生成路由和侧边栏导航的功能。主要步骤如下:

  1. 使用 Vite 的 import.meta.glob 函数获取 components 目录下所有 .vue 文件模块。
  2. 遍历这些模块,提取文件名并构建路由对象。
  3. 将生成的路由对象添加到 Vue Router 的路由配置中。
  4. 在侧边栏中使用 router-link 组件动态渲染导航链接。

路由配置

typescript 复制代码
import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";

// 初始路由配置
const routes: RouteRecordRaw[] = [
    {
        path: '/',
        component: () => import('@/App.vue'),
    }
];

// 定义导入模块的类型接口
interface ImportModule {
    default: {
        __file: string,
        __hrmId: string,
    },
    _rerender_only: boolean
}

// 使用 import.meta.glob 获取 components 目录下所有 .vue 文件模块
const dyn_modules: Record<string, ImportModule> = import.meta.glob('../components/*.vue', {eager: true});

// 遍历模块,构建路由对象并添加到路由配置中
for (let key in dyn_modules) {
    const mod = dyn_modules[key];
    const {__file: file} = mod.default;
    const filename = getName(file); // 获取文件名
    const path = "/" + filename.toLowerCase(); // 构建路径
    routes.push({
        name: filename,
        path: path,
        component: mod.default
    })
}

// 设置 / 路径的重定向目标为第一个动态路由
routes[0].redirect = routes[1]?.path ?? "";

// 提取文件名的辅助函数
function getName(path: string): string {
    let indexOf = path.lastIndexOf("/") + 1;
    let dotIndex = path.lastIndexOf(".");
    return path.substring(indexOf, dotIndex);
}

// 创建路由实例
const router = createRouter({
    history: createWebHistory(),
    routes
})

export default router;

侧边栏导航渲染

html 复制代码
<script setup lang="ts">
  import router from "@/router";
  import { onMounted, ref } from "vue";
  import { RouteRecord } from "vue-router";

  // 存储动态路由记录
  const routes = ref<RouteRecord[]>();

  onMounted(() => {
    // 获取动态路由记录(去除首个静态路由)
    routes.value = router.getRoutes().slice(1);
  })
</script>

<template>
  <div class="flex items-center justify-center h-screen">
    <!-- 路由视图 -->
    <router-view class="w-4/5 h-full"></router-view>
    <div class="w-1/5 h-full">
      <!-- 侧边栏导航 -->
      <ul class="h-full w-full text-2xl p-2 *:px-4 *:py-2 *:bg-blue-50 *:w-full *:block hover:*:bg-blue-300 *:rounded space-y-1.5">
        <router-link v-for="route in routes" class="px-4 py-2 bg-blue-50 w-full block" :to="route.path">{{ route.name }}</router-link>
      </ul>
    </div>
  </div>
</template>

在这个示例中,我们使用 import.meta.glob 函数获取了 components 目录下所有 .vue 文件模块。然后,我们遍历这些模块,提取文件名并构建路由对象。最后,将生成的路由对象添加到 Vue Router 的路由配置中。

在侧边栏中,我们使用 router-link 组件动态渲染导航链接。首先,我们获取了动态路由记录(去除了首个静态路由)。然后,在模板中使用 v-for 遍历这些路由记录,并为每个路由渲染一个 router-link 组件。

注意,我们还设置了一些 CSS 样式,以美化侧边栏导航的外观。

通过这种方式,我们可以动态生成路由和侧边栏导航,而无需手动配置每个路由和导航链接。当您添加或删除 components 目录下的 .vue 文件时,路由和导航将自动更新。

相关推荐
LaughingZhu11 小时前
Product Hunt 每日热榜 | 2026-05-21
前端·人工智能·经验分享·chatgpt·html
怕浪猫11 小时前
Electron 开发实战(一):从零入门核心基础与环境搭建
前端·electron·ai编程
小鹏linux11 小时前
Ubuntu 22.04 部署开源免费具有精美现代web页面的Casdoor账号管理系统
linux·前端·ubuntu·开源·堡垒机
前端若水12 小时前
会话管理:创建、切换、删除对话历史
前端·人工智能·python·react.js
Bigger12 小时前
mini-cc:一个轻量级 AI 编程助手的诞生
前端·ai编程·claude
涵涵(互关)13 小时前
Naive-ui树型选择器只显示根节点
前端·ui·vue
BY组态13 小时前
Ricon组态系统最佳实践:从零开始构建物联网监控平台
前端·物联网·iot·web组态·组态
BY组态13 小时前
Ricon组态系统vs传统组态软件:为什么选择新一代Web组态平台
前端·物联网·iot·web组态·组态
SoaringHeart13 小时前
Flutter进阶:OverlayEntry 插入图层管理器 NOverlayZIndexManager
前端·flutter
放下华子我只抽RuiKe513 小时前
React 从入门到生产(四):自定义 Hook
前端·javascript·人工智能·深度学习·react.js·自然语言处理·前端框架