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

Teach you how to build hive3.1.2 on Tencent Cloud

Environment Preparation Before starting any opera...

Teach you step by step to develop a brick-breaking game with vue3

Preface I wrote a few examples using vue3, and I ...

Install mysql 5.6 from yum source in centos7.4 system

System environment: centos7.4 1. Check whether th...

Introduction to Linux compression and decompression commands

Table of contents Common compression formats: gz ...

Tutorial on installing the unpacked version of mysql5.7 on CentOS 7

1. Unzip the mysql compressed package to the /usr...

Solution to blank page after Vue packaging

1. Solution to the problem that the page is blank...

How to prevent website content from being included in search engines

Usually the goal of building a website is to have...

Summary of Mysql update multi-table joint update method

Next, I will create two tables and execute a seri...

Defining the minimum height of the inline element span

The span tag is often used when making HTML web p...

Steps to install cuda10.1 on Ubuntu 20.04 (graphic tutorial)

Pre-installation preparation The main purpose of ...

Pay attention to the use of HTML tags in web page creation

HTML has attempted to move away from presentation...

Several ways to connect tables in MySQL

The connection method in MySQL table is actually ...