How to import, register and use components in batches in Vue

How to import, register and use components in batches in Vue

Preface

Components are something we use very often. Many people use components by referencing and registering them one file at a time. This article will introduce how to batch introduce, register and use components in Vue.

1. Usage scenarios

In daily development, there is often such a situation:

	import A from 'components/A'
	import B from 'components/B'
	import C from 'components/C'
	import D from 'components/D'

When I encountered this kind of repetitive code, I wondered if I could make the following optimizations and import them all at once. So I found the webpack API and processed it by calling require.context. The specific code is as follows:

2. Usage steps

Involving:

  • The component name is a hyphenated function that will be converted to camelCase.
  • The is property of component;

The detailed explanation is in the code:

1. File Directory

2. HTML code

<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">
      	<!-- Through the is attribute, bind the corresponding component name and display the corresponding component-->
        <component :is="activeComponent"></component>
      </div>
    </div>
  </div>
</template>

3.js code

Syntax: require.context(directory, useSubdirectories, regExp)

  • directory: the file path to search
  • useSubdirectories: whether to search subdirectories
  • regExp: The regular expression to match the file

Return value: two methods and one property

  • keys(): Returns an array of names of successfully matched modules
  • resolve(): accepts a parameter request, which is the relative path of the matching file under the test folder, and returns the relative path of the matching file relative to the entire project
  • id: the id of the execution environment, which is returned as a string. It is mainly used in module.hot.accept, which should be hot loading.
<script>
// Convert the middle horizontal line to camelCase var camelCase = function (s) {
  return s.replace(/-\w/g, function (x) {
    return x.slice(1).toUpperCase();
  });
};
// Import subcomponents in batches, see the syntax above 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$

// Make a component array and register it in the components below 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: "Component A",
        },
        {
          key: "temB",
          tab: "B Component",
        },
        {
          key: "temC",
          tab: "C Components",
        },
        {
          key: "temD",
          tab: "D Components",
        },
      ],
    };
  },
  created() {
    if (this.$route.query["val"]) {
      this.activeComponent = this.$route.query["val"];
    }
  },
  methods: {
    // Switch tab bar tabChangeHandle(val) {
      const {path} = this.$router;

      this.$router.push({
        path,
        query: {val},
      });
      this.activeComponent = val;
    },
  },
};
</script>

4. CSS code (you don’t need to read it, it is written only for code completeness, and can be run and displayed directly)

<style scoped>
.water-analysis {
  height: 100%;
  overflow:auto;
}
.content-box {
  height: 100%;
}
.tab-pane-box {
  height: calc(100% - 62px);
}
</style>

Conclusion

This is the end of this article about how to batch import, register and use Vue components. For more relevant content about batch import of Vue components, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of Vue's method of introducing subcomponents
  • Detailed explanation of how to introduce elementUI components into vue projects
  • Vue's method of introducing all public components at one time in a concise and clear manner
  • Detailed explanation of how to create a new Vue project and introduce the component Element
  • Solve the problem of Vue introducing subcomponent errors
  • How to automatically import Vue components on demand

<<:  How to create a view on multiple tables in MySQL

>>:  Solve the problem of "Welcome to nginx on Fedora!" after installing nginx on Centos7, and there is no default.conf file in the conf.d directory

Recommend

Zabbix monitors mysql instance method

1. Monitoring planning Before creating a monitori...

mysql row column conversion sample code

1. Demand We have three tables. We need to classi...

Docker builds Redis5.0 and mounts data

Table of contents 1. Simple mounting of persisten...

How to install Maven automatically in Linux continuous integration

Unzip the Maven package tar xf apache-maven-3.5.4...

MySQL 8.0.20 installation and configuration method graphic tutorial

MySQL download and installation (version 8.0.20) ...

Steps to transplant the new kernel to the Linux system

1. Download the ubuntu16.04 image and the corresp...

Summary of MySQL stored procedure permission issues

MySQL stored procedures, yes, look like very rare...

A brief understanding of the three principles of adding MySQL indexes

1. The Importance of Indexes Indexes are used to ...

How to run the react project on WeChat official account

Table of contents 1. Use the a tag to preview or ...

In-depth analysis of Flex layout in CSS3

The Flexbox layout module aims to provide a more ...

js realizes the function of clicking to switch cards

This article example shares the specific code of ...

JavaScript BOM location object + navigator object + history object

Table of contents 1. Location Object 1. URL 2. Pr...

Detailed explanation of mysql scheduled tasks (event events)

1. Brief introduction of the event An event is a ...

How to build a new image based on an existing image in Docker

Building new images from existing images is done ...