一般情况下我们是 import A from A.vue,如果组件特别多的情况就比较麻烦,可以通过reqire.content批量注册组件
require.context函数接受三个参数
新建requireComponents.js文件
let webpackComponents = require.context("../components",true,/(\.vue)$/)
let componentsObj = {}
webpackComponents.keys().forEach(key => {
// console.log(key)
var index = key.lastIndexOf("/")
let componentName = key.substring(index+1,key.length).replace(/.vue$/,"")
// console.log(componentName)
let conponentConfig = webpackComponents(key)
componentsObj[componentName] = conponentConfig.default
});
export default componentsObj
组件中使用方法
import componentsObj from "@/utils/requireComponents.js" ;
export default {
name: "home",
components: componentsObj,
data(){
return {}
}
}
注意组件的名字必须唯一,不能有重复