Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

require.context 动态加载 vue 组件 #14

Open
negativeentropy9 opened this issue Nov 2, 2018 · 0 comments
Open

require.context 动态加载 vue 组件 #14

negativeentropy9 opened this issue Nov 2, 2018 · 0 comments
Labels

Comments

@negativeentropy9
Copy link
Owner

negativeentropy9 commented Nov 2, 2018

在引入vue 组件时,通用的解决方案如下:

import A from 'A';
import B from 'B';
...
import Z from 'Z';

以上方法其实也没啥错,可以清楚的看出组件的依赖关系,可是如果有 n 多组件需要引入(其实这种情况基本上没有,尽量把组件拆分成小单元)这种重复的劳动力就没有必要做了,下面介绍一种 通过 require.context 方式来动态引入组件的方式。

import Vue from 'vue';
import upperFirst from 'lodash/upperFirst';

// 获取组件目录下符合 一定 正则表达式的 组件
const requireFn = require.context('../components', false, /\.vue/);

// 获取上下文下的 所有组件
const componentsPathArray = requireFn.keys();

// 组件名称首字母大写
const componentsNameArray = componentsPathArray.map((item) => {
    return upperFirst(item.match(/\.\/(\w+)\.vue/)[1]);
});

// 全局注册组件,此处可以使用 Vue.options.components 查看全局注册的组件
componentsPathArray.forEach((item, index) => {
    Vue.component(componentsNameArray[index], requireFn(item).default);
});

需要注意 require.context 返回的是一个 包含上下文的一个 require 函数,该函数上 包含 keysresolveid 属性。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant