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

相关推荐
前端互助会3 小时前
Live2D形象展示与文本语音播报:打造生动交互体验的完整实现
前端·vue.js·microsoft·交互
努力的小郑5 小时前
今晚Cloudflare一哆嗦,我的加班计划全泡汤
前端·后端·程序员
武昌库里写JAVA5 小时前
微擎服务器配置要求,微擎云主机多少钱一年?
java·vue.js·spring boot·后端·sql
dy17176 小时前
el-table表头上下显示内容
javascript·vue.js·elementui
q***64976 小时前
头歌答案--爬虫实战
java·前端·爬虫
凌波粒6 小时前
SpringMVC基础教程(4)--Ajax/拦截器/文件上传和下载
java·前端·spring·ajax
液态不合群6 小时前
DDD驱动低代码开发:从业务流程到领域模型的全链路设计
前端·低代码·架构·ddd
jonyleek6 小时前
JVS低代码开发中,如何创建自定义前端页面并接入到现有系统中,从创建到接入的全攻略
前端·低代码·前端框架·软件开发
谢尔登7 小时前
【React】React组件的渲染过程分为哪几个阶段?
前端·javascript·react.js
MediaTea7 小时前
Python 第三方库:Flask(轻量级 Web 框架)
开发语言·前端·后端·python·flask