今天就跟大家聊聊有关怎么在vue中批量引入组件,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
一、使用场景
在日常开发中,经常会有这样一种情况:
import A from 'components/A'
import B from 'components/B'
import C from 'components/C'
import D from 'components/D'
遇到这种重复的代码,就在想,是否可以进行以下优化,一次性全部引入。于是就找到了webpack的api,通过调用require.context来进行处理,具体代码如下:
二、使用步骤
涉及到:
具体详解都在代码中:
1.文件目录

2.HTML代码
<template>
<div class="water-analysis">
<div class="content-box" ref="contentbox">
<a-tabs :default-active-key="activeComponent" @change="tabChangeHandle">
<a-tab-pane
v-for="item in tabList"
:key="item.key"
:tab="item.tab"
></a-tab-pane>
</a-tabs>
<div class="tab-pane-box">
<!-- 通过is属性,绑定对应的组件名称,展示对应的组件 -->
<component :is="activeComponent"></component>
</div>
</div>
</div>
</template>
3.js代码
语法:require.context(directory, useSubdirectories, regExp)
返回值:两个方法一个属性
<script>
// 中横线转驼峰
var camelCase = function (s) {
return s.replace(/-\w/g, function (x) {
return x.slice(1).toUpperCase();
});
};
// 批量引入子组件 重点,语法见上
const allComponents = require.context("./comp", false, /\.vue$/);
console.log(allComponents.keys())
// ["./tem-a.vue", "./tem-b.vue", "./tem-c.vue", "./tem-d.vue"]
console.log(allComponents.id)
//./src/views/tempManage/comp sync \.vue$
//制作组件数组,在下方components中注册使用
let resComponents = {};
allComponents.keys().forEach(comName => {
let name = camelCase(comName);
const comp = allComponents(comName);
resComponents[name.replace(/^\.\/(.*)\.\w+$/, "$1")] = comp.default;
});
export default {
name: "WaterQuery",
components: resComponents,
data() {
return {
activeComponent: "temA",
tabList: [
{
key: "temA",
tab: "A组件",
},
{
key: "temB",
tab: "B组件",
},
{
key: "temC",
tab: "C组件",
},
{
key: "temD",
tab: "D组件",
},
],
};
},
created() {
if (this.$route.query["val"]) {
this.activeComponent = this.$route.query["val"];
}
},
methods: {
// 切换tab栏
tabChangeHandle(val) {
const {path} = this.$router;
this.$router.push({
path,
query: {val},
});
this.activeComponent = val;
},
},
};
</script>
4.css代码(可不看,写出来只是为了代码完整性,拿来可以直接运行展示)
<style scoped>
.water-analysis {
height: 100%;
overflow: auto;
}
.content-box {
height: 100%;
}
.tab-pane-box {
height: calc(100% - 62px);
}
</style>
为什么要使用Vue
Vue是一款友好的、多用途且高性能的JavaScript框架,使用vue可以创建可维护性和可测试性更强的代码库,Vue允许可以将一个网页分割成可复用的组件,每个组件都包含属于自己的HTML、CSS、JavaScript,以用来渲染网页中相应的地方,所以越来越多的前端开发者使用vue。
看完上述内容,你们对怎么在vue中批量引入组件有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注天达云行业资讯频道,感谢大家的支持。