vue使用‘require.context()‘局部批量注册组件,并通过component 标签动态绑定组件

一、要点介绍

1.require.context()说明

require.context()方法是webpack的一个api,主要功能是自动导入文件,当导入文件过多时,使用该方法可以统一导入,避免导入不同文件时多行书导入语句,该函数接受三个参数,参数说明如下:
require.context(path,isTraverseSubfolders,regExp)

  1. path:String类型,读取文件的路径
  2. isTraverseSubfolders:Boolean类型,是否遍历文件的子目录
  3. regExp:RegExp类型,匹配文件的正则

2.vue中的component标签说明

vue中的component标签 可以帮我们实现同一个入口调用不同的组件,即自动化实现不同组件的统一调用,通过is属性实现不同组件的绑定,原组件中的属性和方法直接写在component组件中即可 具体请参考以下说明:

原有组件
<componentA :data="xx" @click="xxxx" />
使用component标签调用原有组件
<components :is="componentA" :data="xx" @click="xxxx" />

二、实现过程

1.创建多个组件

在当前文件所在文件夹下创建components文件夹,把所需组件创建在components文件夹下,示例创建三个组件componentA,componentB,componentC;实际开发中我们可以根据需要把组件放置指定的文件夹下,只不过是在通过require.context()方法引入是第一个参数做相应调整即可
在这里插入图片描述

2.在componentTest.vue文件中实现

<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>

猜你喜欢

转载自blog.csdn.net/qw8704149/article/details/113446163