参考官网:https://cn.vuejs.org/v2/guide/components-registration.html 下的:基础组件的自动化全局注册
在日常开发中,为了高效开发,为了避免在开发过程中不停地映日,或者在main.js中不停的注册,或者每增加一个组件就与需要手动去注册一次,所以产生了自动化封装注册全局组件。
1.自定义文件夹
在src下新建一个components文件夹,用于存放组件。并新建一个用于存放需要自动化全局注册的组件,例如lib。
2.自动化封装组件代码片段如下:
// 自动注册组件
// require.context();
// webpack的api,通过执行require.context()函数获取一个特定的上下文结构,主要用来实现自动化模块导入
// 参数:需要检索的目录 是否遍历文件夹 文件正则
const files = require.context(
"@/components",
true,
/^\.\/(\w*\/)+index\.(vue|js)$/
);
// console.log(files, '^^^'); // 函数
// console.log(files.keys()); // 组件文件 数组
export default Vue => {
// 循环遍历文件数组
files.keys().forEach(path => {
// console.log(files(path))
const file = files(path).default;
// console.log(file)
const type = componentType(file);
if (type === "plugin") {
Vue.use(file);
} else if (type === "component") {
Vue.component(file.name, file);
} else {
Object.keys(file).forEach(key => {
Vue.component(file[key].name, file[key]);
});
}
});
};
const componentType = file => {
if (typeof file === "function" || file.install) {
// 插件
return "plugin";
} else if (file.name) {
// 组件
return "component";
} else {
return "componentGroup";
}
};
以上代码需要解释的地方:
1、匹配基础组件文件名的正则表达式,此处需要根据实际的组件名称和规则进行配置;
2、componentConfig.default.name此处用到的,是表示组件的名称,并不是固定的写法。可以用不同的写法来表示组件名称,例如可以直接解析fileName得出文件夹的名称作为组件名称也是可以的。componentConfig.default.name中的name,来自于组件定义的时候页面的name。若页面没有定义name,则报错。
3.在main.js中引入刚写好的代码片段 autoInstallComponents.js
import autoInstallComponents from './lib/autoInstallComponents' // 全局组件统一声明
引入main.js 后使用vue实例化
Vue.use(autoInstallComponents)
4.直接在该使用的地方使用组件
<template>
<div class="home">
<HelloWorld></HelloWorld>
</div>
</template>
<script>
export default {
name: "Home",
mounted() {
console.log(this.$options.components);
},
};
</script>
效果如下: