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

相关推荐
东方翱翔6 分钟前
CSS的三种基本选择器
前端·css
Fan_web29 分钟前
JavaScript高级——闭包应用-自定义js模块
开发语言·前端·javascript·css·html
yanglamei196236 分钟前
基于GIKT深度知识追踪模型的习题推荐系统源代码+数据库+使用说明,后端采用flask,前端采用vue
前端·数据库·flask
千穹凌帝37 分钟前
SpinalHDL之结构(二)
开发语言·前端·fpga开发
冯宝宝^41 分钟前
基于mongodb+flask(Python)+vue的实验室器材管理系统
vue.js·python·flask
dot.Net安全矩阵1 小时前
.NET内网实战:通过命令行解密Web.config
前端·学习·安全·web安全·矩阵·.net
Hellc0071 小时前
MacOS升级ruby版本
前端·macos·ruby
前端西瓜哥1 小时前
贝塞尔曲线算法:求贝塞尔曲线和直线的交点
前端·算法
又写了一天BUG1 小时前
npm install安装缓慢及npm更换源
前端·npm·node.js
cc蒲公英1 小时前
Vue2+vue-office/excel 实现在线加载Excel文件预览
前端·vue.js·excel