背景
Vue中的<component>标签支持我们通过传is属性去解析成对应的组件,可以少写很多重复的不同组件相同配置的html
但是发现了一个问题就是每一个组件我都需要去引入一遍,很机械,代码也会越来越多
思路
使用webpack的api,通过require.context去获取到某个文件夹下的vue文件,自动引入这些组件,再去注册他,减少无意义的每次引入
Vue3实现
<template>
<component :is="xxxx">
</template>
<script lang="ts">
import { defineComponent} from 'vue';
type AnyKey = {
[x: string]: any;
};
// 自动加载components文件夹下的组件,第一个参数是文件夹路径,第二个参数是是否递归子文件夹,第三个参数是文件名匹配正则
const allComponents = require.context('./components', false, /\.vue$/);
// 用于收集导入组件的对象,假如页面有导入其他组件xxxx可以先写在初始值里面const components = {xxxx}
const components: AnyKey = { };
// 收集到的导入组件进行遍历,以文件名作为key,导入文件的默认导出为value值,存入components对象
allComponents.keys().forEach((fileName: string) => {
const comp = allComponents(fileName);
// 截掉文件名后缀
components[`${fileName.replace(/^\.\/(.*)\.\w+$/, '$1')}`] = comp.default;
});
export default defineComponent({
// 注册组件
components,
})
</script>