前言

组件是我们非常常用的东西,很多人使用组件都是通过一个一个文件去引用和注册。这篇文章就来介绍下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来进行处理,具体代码如下:

二、使用步骤

涉及到:

  • 组件名称为带中横线规范,最后要转为驼峰命名法的功能;
  • component的is属性;

具体详解都在代码中:

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)

  • directory: 要查找的文件路径
  • useSubdirectories: 是否查找子目录
  • regExp: 要匹配文件的正则

返回值:两个方法一个属性

  • keys(): 返回匹配成功模块的名字组成的数组
  • resolve(): 接受一个参数request,request为test文件夹下面匹配文件的相对路径,返回这个匹配文件相对于整个工程的相对路径
  • id:执行环境的id,返回的是一个字符串,主要用在module.hot.accept,应该是热加载
<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批量引入组件内容请搜索悠悠之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持悠悠之家!

点赞(170)

评论列表共有 0 条评论

立即
投稿
返回
顶部