import Vue from 'vue'
const componentsContext = require.context('./components', true, /index.vue$/)
componentsContext.keys().forEach(component => {
// 获取文件中的 default 模块
const componentConfig = componentsContext(component).default
Vue.component(componentConfig.name, componentConfig)
})
首先通过 require.context() 获取 ./components 目录下所有文件夹里的 index.vue 文件,然后循环依次读取文件中的 default 模块,并使用组件的 name 做为组件名进行组件注册。
需要注意的是,组件必须设置 name 值,因为注册的组件名就是 name 值,所以还要确保不能重名。
export default {
name: 'ExampleComponent1'
}