likes
comments
collection
share

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

作者站长头像
站长
· 阅读数 7

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

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

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

路由配置

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;

侧边栏导航渲染

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

转载自:https://juejin.cn/post/7344571313686003724
评论
请登录