项目中动态配置路由可以减少路由配置时间,并可减少配置路由出现的一些奇奇怪怪的问题
路由配置化可统一定义相关属性等
本文记录vite
和webppack
两种构建工具配置动态路由,
页面定义最好同时定义对应的
title
及name
值
page-template
为例import { defineComponent, h, defineAsyncComponent } from 'vue';
const PageComponent = defineAsyncComponent(() => import('./components/index.vue'));
export default defineComponent({
// 配置后可在 动态获取路由配置中设置对应值
title: '页面模版',
name: 'PageTemplate',
setup() {
return () => h(PageComponent);
},
});
import { defineComponent } from 'vue'
export default defineComponent({
setup() {
return {
};
},
});
<script lang="ts" src="./index.ts" />
<template>
<div>templatediv>
template>
<style scoped lang="less">style>
vite使用import.meta.glob
动态获取文件
/router/utils.ts
/**
* 路由配置文件
*/
import { DEFAULT_DOCUMENT_TITLE } from '@/const/base';
import type { RouteRecordRaw } from 'vue-router';
function getComponent() {
return import.meta.glob('../views/**/index.ts', { eager: true });
}
// 获取路由文件
export const vueRouters = (): RouteRecordRaw[] => {
const routerList: RouteRecordRaw[] = [];
const files = getComponent();
Object.keys(files).forEach((fileSrc: string) => {
const component = files[fileSrc] as any;
const componentPath = fileSrc.replace(/^\.\//, '');
const routerPath = componentPath.replace('../views', '').replace(/\/index.ts$/, '');
if (!componentPath.includes('components')) {
routerList.push({
path: routerPath,
name: component.default.name,
component: () => import(/* @vite-ignore */componentPath),
meta: {
title: component.default.title || DEFAULT_DOCUMENT_TITLE,
// skeleton: component.skeleton, // TODO 待处理页面骨架屏
// background: component.backgroundColor, // TODO 待处理页面级别颜色
},
});
}
});
return routerList;
};
/router/utils.ts
/router/index.ts
import { createRouter, createWebHistory } from "vue-router";
import HomeView from "@/views/layout/index";
import { vueRouters } from "./utils";
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
......vueRouters()
],
});
export default router;
webpack使用require.context
获取文件路径
/router/utils.ts
/**
* 路由配置文件
*/
import { DEFAULT_DOCUMENT_TITLE } from '@/const/base';
import type { RouteRecordRaw } from 'vue-router';
function getComponent() {
return require.context('../views', true, /\.ts$/);
}
// 获取路由文件
export const vueRouters = (): RouteRecordRaw[] => {
const routerList: RouteRecordRaw[] = [];
const requireRouters = getComponent();
requireRouters.keys().forEach((fileSrc: string) => {
const viewSrc = requireRouters(fileSrc);
const component = viewSrc.default;
const componentPath = fileSrc.replace(/^\.\//, '');
const routerPath = componentPath.replace(/(\S+)index.ts$/, '/$1index.html');
if (component.name !== 'Home' && !component.isOffLine) {
routerList.push({
path: routerPath,
name: component.name,
component: () => import(`@/views/${componentPath}`),
meta: {
title: component.title || DEFAULT_DOCUMENT_TITLE,
},
});
}
});
return routerList;
};
export default vueRouters();
使用同vite
vite 和 webpack 不同于获取文件格式,获取后的操作基本一致
如有启发,可点赞收藏哟~