使用 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 文件时,路由和导航将自动更新。

相关推荐
大怪v6 小时前
AI抢饭?前端佬:我要验牌!
前端·人工智能·程序员
新酱爱学习6 小时前
字节外包一年,我的技术成长之路
前端·程序员·年终总结
小兵张健6 小时前
开源 playwright-pool 会话池来了
前端·javascript·github
IT_陈寒9 小时前
Python开发者必知的5大性能陷阱:90%的人都踩过的坑!
前端·人工智能·后端
codingWhat9 小时前
介绍一个手势识别库——AlloyFinger
前端·javascript·vue.js
代码老中医9 小时前
2026年CSS彻底疯了:这6个新特性让我删掉了三分之一JS代码
前端
不会敲代码19 小时前
Zustand:轻量级状态管理,从入门到实践
前端·typescript
踩着两条虫9 小时前
VTJ.PRO 双向代码转换原理揭秘
前端·vue.js·人工智能
扉川川9 小时前
OpenClaw 架构解析:一个生产级 AI Agent 是如何设计的
前端·人工智能
远山枫谷10 小时前
一文理清页面/组件通信与 Store 全局状态管理
前端·微信小程序