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

A question about border-radius value setting

Problem Record Today I was going to complete a sm...

How to build a multi-node Elastic stack cluster on RHEL8 /CentOS8

Elastic stack, commonly known as ELK stack, is a ...

Detailed example of deploying Nginx+Apache dynamic and static separation

Introduction to Nginx dynamic and static separati...

Analysis of Nginx Rewrite usage scenarios and configuration methods

Nginx Rewrite usage scenarios 1. URL address jump...

Vue.js framework implements shopping cart function

This article shares the specific code of Vue.js f...

Introduction to setting up Tomcat to start automatically on Linux system

1. Enter the /etc/init.d directory: cd /etc/init....

JavaScript article will show you how to play with web forms

1. Introduction Earlier we introduced the rapid d...

mysql startup failure problem and scenario analysis

1. One-stop solution 1. Problem analysis and loca...

Example of using negative margin to achieve average layout in CSS

For evenly distributed layouts, we generally use ...

A brief discussion on JavaScript throttling and anti-shake

Table of contents Throttling and anti-shake conce...

Tutorial on using iostat command in Linux

Preface It is said that if the people doing opera...

MySQL slow_log table cannot be modified to innodb engine detailed explanation

background Getting the slow query log from mysql....

Springboot+Vue-Cropper realizes the effect of avatar cutting and uploading

Use the Vue-Cropper component to upload avatars. ...

Vue-cli creates a project and analyzes the project structure

Table of contents 1. Enter a directory and create...

How to install and configure the supervisor daemon under centos7

Newbie, record it yourself 1. Install supervisor....