vue中自动生成路由配置文件覆盖路由配置
设计思路
- 读取
@/views
下所有index.vue
如果当前文件下有包含相同路径则认为是它的子路由。 - 但也不能就这样写死,要创建
page.(ts|js)
配置文件也可以更改当前的配置,page.(ts|js)
比重大于自动生成的路由配置。
踩坑点
坑点1
这里的'@/views'
不能使用变量传入。
(require as any).context('@/views', true, /index\.vue$/)
坑点2
这里如果想对文件进行深度拷贝,直接使用三点(…)是不行的,这里借助了loadsh
中的merge
完成深度拷贝。
// 导出当前存在的路由并重新赋值 const existingroute = routemap[route.path]; // 当前路由存在 if (existingroute) { const exportrouteconfig = context(fileinfo?.filepath).default; // 使用loadsh合并对象 routemap[route.path] = _.merge(existingroute, exportrouteconfig); }
代码编写
在vue中自动生成路由,并将目录下配置文件覆盖到原先路由配置。
import { routefilenamehelper } from '@/utils/file/routefileutil'; import _ from 'lodash'; import { routerecordraw } from 'vue-router'; // * 最终路由 const routemap: record<string, routerecordraw> = {}; // * 所有处理的路由 const contexts = [ { context: (require as any).context('@/views', true, /index\.vue$/), isindex: true }, { context: (require as any).context('@/views', true, /page\.(ts|js)$/), isindex: false }, ]; /** * 构建路由信息 * @param context 上下文信息 * @param isindex 是否第一次遍历 * @param route 路由内容 */ function buildroutetree(context: any, isindex: boolean, route: any) { // 遍历当前子路由 context.keys().foreach((item: string) => { // 获取子路由下所有文件对象格式 const childrenfileinfo = routefilenamehelper(item, '/'); // 组装子路由对象 const childrenroute: any = { name: childrenfileinfo?.name, path: childrenfileinfo!.path, component: isindex ? () => import(`@/views${childrenfileinfo?.replacename}`) : undefined, children: [], meta: { isfullscreen: false }, }; // 如果当前路由对象等于当前遍历的路由子对象,将子路由推到父级路由中 if (childrenfileinfo?.path.includes(route.path) && childrenfileinfo?.path !== route.path) { route.children.push(childrenroute); } }); } /** * 遍历路由信息 * @param context 路由上下文 * @param isindex 是否为索引遍历 */ const createroutelist = (context: any, isindex: boolean) => { // 遍历文件下所有路径 context.keys().foreach((filepath: string) => { const fileinfo = routefilenamehelper(filepath, '/'); // 组装路由对象 const route: routerecordraw = { name: fileinfo?.name, path: fileinfo!.path, component: isindex ? () => import(`@/views${fileinfo?.replacename}`) : undefined, children: [], meta: { isfullscreen: false }, }; // * 如果是第一次遍历 初始化赋值 if (isindex) { routemap[route.path] = route; buildroutetree(context, isindex, route); } // * 读取配置文件中内容 else { // 导出当前存在的路由并重新赋值 const existingroute = routemap[route.path]; // 当前路由存在 if (existingroute) { const exportrouteconfig = context(fileinfo?.filepath).default; // 使用loadsh合并对象 routemap[route.path] = _.merge(existingroute, exportrouteconfig); } } }); }; // * 生成路由信息 contexts.foreach(({ context, isindex }) => createroutelist(context, isindex)); // * 返回生成好的路由 export const pageroutes: array<routerecordraw> = object.values(routemap);
到此这篇关于vue中自动生成路由配置文件覆盖路由配置的文章就介绍到这了,更多相关vue自动生成路由配置文件内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论