Vue uses'require.context()' to locally register components in batches, and dynamically bind components through the component tag

1. Introduction

1.require.context() description

The require.context() method is an api of webpack. The main function is to automatically import files. When there are too many files to be imported, this method can be used to import in a unified manner to avoid multi-line import statements when importing different files. This function accepts three parameters. The description is as follows:
require.context(path,isTraverseSubfolders,regExp)

  1. path: String type, the path to read the file
  2. isTraverseSubfolders: Boolean type, whether to traverse the subfolders of the file
  3. regExp: RegExp type, the regularity of matching files

2. Component tag description in vue

The component tag in vue can help us to call different components at the same entry point, that is, to automatically realize the unified call of different components, and realize the binding of different components through the is attribute. The properties and methods in the original component are directly written in the component component. For details, please refer to the following instructions:

Original component
<componentA :data="xx" @click="xxxx" />
Use the component tag to call the original component
<components :is="componentA" :data="xx" @click="xxxx" />

Second, the realization process

1. Create multiple components

Create the components folder in the folder where the current file is located, and create the required components in the components folder. The example creates three components componentA, componentB, and componentC; in actual development, we can place the components in the specified folder as needed. It's just that the first parameter is introduced through the require.context() method and adjusted accordingly.
Insert picture description here

2. Implemented in the componentTest.vue file

<template>
  <div>
    <div v-for="componentName in componentList" :key="componentName">
      <components :is="componentName" />
    </div>
  </div>
</template>
<script>

const requireComponents = require.context('./components/', false, /\.vue$/) //读取当前文件夹下components文件夹下.vue文件
const componentsObj = {
    
     }
requireComponents.keys().forEach(filePath => {
    
    
  const componentName = filePath.split('/')[1].replace(/\.vue$/, '')
  const componentConfig = requireComponents(filePath)
  componentsObj[componentName] = componentConfig.default || componentConfig
})
export default {
    
    
  components: componentsObj,

  data() {
    
    
    return {
    
    
      componentList: ['componentA', 'componentB', 'componentC']
    }
  },
  computed: {
    
    },

  mounted() {
    
    },
  methods: {
    
    }
}
</script>

Guess you like

Origin blog.csdn.net/qw8704149/article/details/113446163