Vue-Nuxt的动态路由如何实现的?

466 阅读1分钟

了解nuxt的动态路由,只需要按规则写页面名称就自动注入路由,这个挺好的,因为每次我们开发有代码规范,其中就包括文件、文件夹命名规范。例如我们写的页面放“views”目录下,这样才能保证整个团队开发效率。nuxt.com/docs/guide/…

有点扯远了,对于开发来说我们在views创建页面,其实就是我们路由需要展示,并且文件名就是路由的path

实现router/index.ts

import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";

const allViews = require.context("../views", true, /\.vue$/);
const routes: Array<RouteRecordRaw> = [];
const filePathList = allViews.keys();
const fileNameReplace = (fileName: string) =>
  fileName.replace(/\[([\w\-_]*)\]/g, ($0, $1) => `:${$1}`);
const pathToChildren: any = {};

filePathList.forEach((filePath) => {
  const result = filePath.slice(2, -4);
  const fileNameList = result.split("/");
  const fileNameLen = fileNameList.length;
  let relativePath = "";
  let routersParent = routes;
  const children: any = [];
  const path = fileNameList.map((x) => fileNameReplace(x)).join("/");

  for (let i = 0; i < fileNameLen; i++) {
    const rightIndex = fileNameLen - 1 - i;
    const left = fileNameList
      .slice(0, rightIndex)
      .map((x) => fileNameReplace(x))
      .join("/");
    const fileName = fileNameReplace(fileNameList[rightIndex]);

    if (i === 0) {
      if (fileName === "index") {
        relativePath = "";
      } else {
        relativePath = fileName;
      }
    } else {
      relativePath = fileName + "/" + relativePath;
    }

    if (i === fileNameList.length - 1) {
      relativePath = "/" + relativePath;
    }

    if (filePathList.includes(`./${left}.vue`)) {
      routersParent = pathToChildren[left];
      break;
    }
  }

  pathToChildren[path] = children;

  routersParent.push({
    path: `${relativePath}`,
    // name: fileName,
    component: () => import(`../views/${result}.vue`),
    children,
  });
});

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

export default router;

查看效果

2023-07-15 10.54.53.gif

由于codesandbox上传不了模板,需要的请留言