Vite+vue3的约定式路由实践

  • Vite+vue3的约定式路由实践;
  • 实现了类似umi的约定式路由,并实现了全局layouts的和404的路由;
  • 本文大量借鉴了下面链接的文章,侵权删

路由规则

生成的方式,我们尽量与 umi.js 保持一致, 并实现(umijs)的约定式 layouts404路由。但避免一个问题:避免将不需要的组件映射成路由

  • pages/index.tsx/
  • pages/blog/index.tsx/blog
  • pages/about.tsx/about

umi中,我们可以在config.ts中这样配置来避免将不需要的组件映射成路由

javascript 复制代码
conventionRoutes: {
    // 规定只有index文件会被识别成路由
    exclude: [
      /(?<!(index|\[index\]|404)(\.(js|jsx|ts|tsx)))$/,
      /model\.(j|t)sx?$/,
      /\.test\.(j|t)sx?$/,
      /service\.(j|t)sx?$/,
      /models\//,
      /components\//,
      /services\//,
    ],
  },

在这里,我们暂时使用这个正则,也可以根据项目中是否使用了jsx来增加.vue文件后缀

ini 复制代码
const modules = import.meta.glob("/src/pages/**/{index,404}.{ts,tsx}");

工程目录示例

复制代码
├─layouts
│  │  index.tsx
├─pages
│  │
│  └─demo
│      │  index.tsx
│      │
│      └─demo-child
│              hello-world.tsx
│              index.tsx

话不多说,直接上代码

route/plugin.ts 复制代码
import { set } from "lodash-es";

import type { RouteRecordRaw } from "vue-router";
/**
 * 根据 pages 目录生成路径配置
 */
function generatePathConfig(): Record<string, any> {
  // 扫描 src/pages 下的所有具有路由文件
  const modules = import.meta.glob("/src/pages/**/{index,404}.{ts,tsx}");

  const pathConfig = {};
  Object.keys(modules).forEach((filePath) => {
    const routePath = filePath
      // 去除 src/pages 不相关的字符
      .replace("/src/pages/", "")
      // 去除文件名后缀
      .replace(/.tsx?/, "")
      // 转换动态路由 $[foo].tsx => :foo
      .replace(/\$\[([\w-]+)]/, ":$1")
      // 转换以 $ 开头的文件
      .replace(/\$([\w-]+)/, "$1")
      // 以目录分隔
      .split("/");
    // 使用 lodash.set 合并为一个对象
    set(pathConfig, routePath, modules[filePath]);
  });
  return pathConfig;
}

/**
 * 将文件路径配置映射为 vue-router 路由
 */
function mapPathConfigToRoute(cfg: Record<string, any>): RouteRecordRaw[] {
  // route 的子节点为数组
  return Object.entries(cfg).map(([routePath, child]): RouteRecordRaw => {
    let currentRoute: RouteRecordRaw = {
      path: routePath,
      name: routePath,
    };
    // () => import() 语法判断 转换为组件
    if (typeof child.index === "function" || typeof child === "function") {
      currentRoute.component = child.index || child;
    }
    const { index, ...rest } = child;
    // 还有子级为目录,查找下一层级
    if (Object.keys(rest).length > 0) {
      currentRoute.children = mapPathConfigToRoute(rest);
    }
    return currentRoute;
  });
}

// 提取公共layouts
const getLayouts = (): (() => Promise<any>) => {
  const layouts = import.meta.glob("/src/layouts/index.{ts,tsx}");
  if (!layouts) return () => Promise.resolve(undefined);
  return Object.entries(layouts)[0][1];
};

function generateRouteConfig(): RouteRecordRaw[] {
  const { ...pathConfig } = generatePathConfig();
  return [
    {
      path: "",
      name: "",
      component: getLayouts(),
      children: mapPathConfigToRoute(pathConfig),
    },
    { path: "/:pathMatch(.*)*", redirect: "/404" },
  ];
}

const routeConfig = generateRouteConfig();
export { routeConfig };

在router中使用

typescript 复制代码
import { createRouter, createWebHistory } from "vue-router";
import { routeConfig } from "./plugin";

const router = createRouter({
  history: createWebHistory(""),
  routes: routeConfig,
});

router.beforeEach(async (to: any) => {
  
});

router.afterEach(() => {
  
});

export default router;

结语

暂无

相关推荐
科技D人生8 分钟前
Vue.js 学习总结(20)—— Vue-Office 实战:word、pdf、excel、ppt 多种文档的在线预览
vue.js·word·vue-pdf·stylesheet·docx-preview·vue-office
vx1_Biye_Design10 分钟前
基于Spring Boot+Vue的学生管理系统设计与实现-计算机毕业设计源码46223
java·vue.js·spring boot·spring·eclipse·tomcat·maven
vx_Biye_Design11 分钟前
基于Spring Boot+vue的湖北旅游景点门票预约平台的设计--毕设附源码29593
java·vue.js·spring boot·spring cloud·servlet·eclipse·课程设计
hedley(●'◡'●)11 分钟前
基于cesium和vue的大疆司空模仿程序
前端·javascript·vue.js·python·typescript·无人机
qq5_81151751513 分钟前
web城乡居民基本医疗信息管理系统信息管理系统源码-SpringBoot后端+Vue前端+MySQL【可直接运行】
前端·vue.js·spring boot
百思可瑞教育13 分钟前
构建自己的Vue UI组件库:从设计到发布
前端·javascript·vue.js·ui·百思可瑞教育·北京百思教育
百锦再13 分钟前
Vue高阶知识:利用 defineModel 特性开发搜索组件组合
前端·vue.js·学习·flutter·typescript·前端框架
hdsoft_huge16 分钟前
1panel面板中部署SpringBoot和Vue前后端分离系统 【图文教程】
vue.js·spring boot·后端
这儿有一堆花1 小时前
Vue 是什么:一套为「真实业务」而生的前端框架
前端·vue.js·前端框架
NCDS程序员1 小时前
v-model: /v-model/ :(v-bind)三者核心区别
前端·javascript·vue.js