實現效果,配置了layout和對應的路由的meta
- 我想每個模塊添加對應的layout,下邊演示一層layout及對應的路由
約束規則:
每個模塊下,添加對應的 layout.vue
文件
每個文件夾下的 index.vue
是要渲染的頁面路由
每個渲染的頁面路由對應的 page.json
是要配置的路由的meta
以下demo目錄結構,頁面放到了pages下,如果你是在其它文件夾名字,請自己修改
以上路徑會生成如下結構
[{"path": "/admin","meta": {"title": "管理系統","isAuth": true},"children": [{"path": "/admin/about","meta": {"title": "關于我們","isAuth": true}},{"path": "/admin/home","meta": {}}],"redirect": "/admin/home"},{"path": "/crm","meta": {},"children": [{"path": "/crm/dust","meta": {}}],"redirect": "/crm/dust"}
]
直接上代碼了,多級有需要的自己遞歸下
- router/index.ts
import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router';// page module
const pagesModule = import.meta.glob('@/pages/**/index.vue');// layout module
const layoutModule = import.meta.glob('@/pages/**/layout.vue');// 獲取路由頁面的配置
const pagesConfig = import.meta.glob('@/pages/**/page.json', {eager: true,import: 'default'
});// 處理路徑
function getPath(path: string, tag: string) {return path.replace('/src/pages', '').replace(`/${tag}.vue`, '');
}// 獲取頁面配置meta
function getMeta(path: string, tag: string): any {return pagesConfig[path.replace(`${tag}.vue`, 'page.json')] || {};
}// 生成layout下路由
function genChildrenRouter(layoutKey: string, obj: any) {const LAYOUT_KEY = layoutKey.replace('/layout.vue', '');for (const pageKey in pagesModule) {if (pageKey.includes(LAYOUT_KEY)) {obj.redirect = getPath(pageKey, 'index');obj.children.push({path: getPath(pageKey, 'index'),component: pagesModule[pageKey],meta: getMeta(pageKey, 'index')});}}
}// 生成layout
function genLayout() {const layoutList = [];for (const layoutKey in layoutModule) {const obj: RouteRecordRaw = {path: getPath(layoutKey, 'layout'),component: layoutModule[layoutKey],meta: getMeta(layoutKey, 'layout'),children: []};genChildrenRouter(layoutKey, obj);layoutList.push(obj);}return layoutList;
}// 最終的結果
const routerList = genLayout();const router = createRouter({history: createWebHistory(import.meta.env.BASE_URL),routes: [{path: '/',redirect: routerList[1].path},...routerList]
});export default router;