当前位置:   article > 正文

【vue进阶】优雅自动引入自动注册Vue组件_vue component 自动引入并注册

vue component 自动引入并注册

随着项目的不断变大,可能有些人会把插件的引入和全局组件的注册都放到main.js中,导致后面main.js里面一大坨引入代码,看起来杂乱无比,也不利于后期进行维护,所以我们尽可能的让main.js看起来整洁些。此处就用到webpack的require.context功能,实现Vue自动注册全局组件及插件,方便全局组件和插件的管理。

在Vue项目开发中,经常需要import或者export各种模块,当一个页面中组件很多时,我们可能会这样引入组件:

import A from 'components/A.vue'
import B from 'components/B.vue'
import C from 'components/C.vue'
import D from 'components/D.vue'
  • 1
  • 2
  • 3
  • 4

要是每加一个组件,都要写这么一句 import ,那岂不是很蛋疼,是否可以通过自动化引入呢?

答案是肯定有的,那就要使用 webpack 给我们提供的 require.context API:

require.context(directory, useSubdirectories, regExp)
  • 1

它接收三个参数:

  • directory: 要查找的文件路径
  • useSubdirectories: 是否查找子目录
  • regExp: 要匹配文件的正则
    比如我在根目录 src/components下包含多级子目录的组件,如下图:
    在这里插入图片描述
const requireComponent = require.context('../src/components/', true, /\w+\.(vue||js)$/)
  • 1

我们可以打印一下 ctx,看返回的是什么内容:

var map = {
	"./A.vue": "./src/components/A.vue",
	"./B.vue": "./src/components/B.vue",
	"./C.vue": "./src/components/C.vue",
	"./D.vue": "./src/components/D.vue"
};


function webpackContext(req) {
	var id = webpackContextResolve(req);
	return __webpack_require__(id);
}
function webpackContextResolve(req) {
	var id = map[req];
	if(!(id + 1)) { // check for number or string
		var e = new Error("Cannot find module '" + req + "'");
		e.code = 'MODULE_NOT_FOUND';
		throw e;
	}
	return id;
}
webpackContext.keys = function webpackContextKeys() {
	return Object.keys(map);
};
webpackContext.resolve = webpackContextResolve;
module.exports = webpackContext;
webpackContext.id = "./src/components sync recursive \\.vue$";

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

从打印结果可以看出,require.context执行后,返回一个方法 webpackContext,这个方法又返回一个__webpack_require__,__webpack_require__就相当于require或者import。

同时 webpackContext 还有两个静态方法 keys 与 resolve,一个 id 属性。

  • keys:返回匹配成功模块的名字组成的数组;
  • resolve:接受一个参数request,request为 ./src/components
    文件夹下面匹配文件的相对路径,返回这个匹配文件相对于整个工程的相对路径;
  • id:执行环境的id,返回的是一个字符串,主要用在module.hot.accept,应该是热加载看下keys是作用。

这样一来,通过 ctx.keys() 我们可以得到匹配文件的相对路径数组:

["./HelloWorld.vue", "./tools/abs/bl-pua.vue", "./tools/foot.vue"]
  • 1

基于以上数组,我们就可以封装一个自动引入组件的方法了,比如在 plugins文件夹下创建 componentsRegister.js 文件:

/**
* 自动注册组件
*/
export default {
  install (Vue) {
    const requireComponent = require.context('../src/components/', true, /\w+\.(vue|js)$/)
    requireComponent.keys().forEach(fileName => {
    	// 这个地方直接传入fileName其实就是内部会调用了resolve方法,会返回对应的文件内容(不理解可以console一下看看)
        const config = requireComponent(fileName);
        // 获取组件的 PascalCase 命名
        const componentName = fileName.split('/').pop().replace(/\.\w+$/, '');

        // 动态注册该目录下的所有.vue文件
        // 如果这个组件选项是通过 `export default` 导出的,
	    // 那么就会优先使用 `.default`,
	    // 否则回退到使用模块的根。
        Vue.component(componentName, config.default || config); 
    })
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

最后在入口文件 main.js 中导入封装好的文件,即可实现组件的自动化引入:

import Vue from 'vue'
// 自动引入处理组件插件
import componentsList from '../plugins/componentsRegister';
Vue.use(componentsList);
  • 1
  • 2
  • 3
  • 4
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/86267
推荐阅读
  

闽ICP备14008679号