1.在每一个views文件夹中创建page.js配置文件,作为路由的meta选项配置
export default {
title: "首页",
};
2.在router中使用import.meta.glob加载所有的路由模块
import { createRouter, createWebHistory } from "vue-router";
const pages = import.meta.glob("../views/**/page.js", {
eager: true,
import: "default",
});
const pageComps = import.meta.glob("../views/**/index.vue");
const routes = Object.entries(pages).map(([path, meta]) => {
const pageJsPath = path;
path = path.replace("../views", "").replace("/page.js", "");
path = path || "/";
const compsPath = pageJsPath.replace("page.js", "index.vue");
const name = path.split("/").filter(Boolean).join("-") || "index";
return {
path,
name,
component: pageComps[compsPath],
meta,
children: [],
};
});
const newRoutes = routes.find((item) => item.name === "index");
const filterRoutes = routes.filter((item) => item.name !== "index");
filterRoutes.forEach((item) => {
newRoutes.children.push(item);
});
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [newRoutes],
});
router.beforeEach((to, from, next) => {
document.title = to.meta.title;
next();
});
export default router;