首先将路由配置拆分到每个目录下,以Dashboard为例:
每个目录下都有一个route文件夹,保存各自菜单的单个路由信息
读取目录下route信息,并按目录结构组装的相关代码如下:
const routeModuleList: AppRouteModule[] = [];
// const modules = import.meta.globEager('./modules/**/*.ts');
const modules = import.meta.globEager('../../views/**/route/*.ts');
const temp: [] = [];
Object.keys(modules).forEach((rmkey) => {
console.log(rmkey.split('/'));
if (!temp[rmkey.split('/').length - 6]) {
temp[rmkey.split('/').length - 6] = [];
temp[rmkey.split('/').length - 6].push(rmkey);
} else {
temp[rmkey.split('/').length - 6].push(rmkey);
}
});
for (let i = 0; i < temp.length; i++) {
if (temp[i + 1]) {
for (let j = 0; j < temp[i].length; j++) {
const moduleRoute = modules[temp[i][j]].default;
const pkey = temp[i][j].substring(0, temp[i][j].indexOf('/route/index.ts'));
for (let k = 0; k < temp[i + 1].length; k++) {
if (temp[i + 1][k].indexOf(pkey) > -1) {
if (moduleRoute.children) {
moduleRoute.children.push(modules[temp[i + 1][k]].default);
} else {
moduleRoute.children = [];
moduleRoute.children.push(modules[temp[i + 1][k]].default);
}
}
}
routeModuleList.push(moduleRoute);
}
} else {
break;
}
}
export const asyncRoutes = [PAGE_NOT_FOUND_ROUTE, ...routeModuleList];
最后页面只会根据目录下route的信息生成组件树: