实现效果,配置了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;