Vueは「require.context()」を使用してコンポーネントをバッチでローカルに登録し、コンポーネントタグを介してコンポーネントを動的にバインドします

1.はじめに

1.require.context()の説明

require.context()メソッドはwebpackのAPIです。主な機能はファイルを自動的にインポートすることです。インポートするファイルが多すぎる場合、このメソッドを使用して統一された方法でインポートし、複数行のインポートステートメントを回避できます。異なるファイルをインポートする場合。この関数は3つのパラメーターを受け入れます。説明は次のとおりです
。require.context(path、isTraverseSubfolders、regExp)

  1. パス:文字列タイプ、ファイルを読み取るパス
  2. isTraverseSubfolders:ブール型。ファイルのサブフォルダーをトラバースするかどうか
  3. regExp:RegExpタイプ、一致するファイルの規則性

2.vueでのコンポーネントタグの説明

vueのcomponentタグは、同じエントリポイントでさまざまなコンポーネントを呼び出すのに役立ちます。つまり、さまざまなコンポーネントの統合呼び出しを自動的に実現し、is属性を介してさまざまなコンポーネントのバインディングを実現します。元のプロパティとメソッドコンポーネントはコンポーネントコンポーネントに直接書き込まれます。詳細については、次の手順を参照してください。

元のコンポーネント
<componentA :data="xx" @click="xxxx" />
コンポーネントタグを使用して、元のコンポーネントを呼び出します
<components :is="componentA" :data="xx" @click="xxxx" />

第二に、実現プロセス

1.複数のコンポーネントを作成します

現在のファイルが配置されているフォルダーにcomponentsフォルダーを作成し、componentsフォルダーに必要なコンポーネントを作成します。この例では、componentA、componentB、componentCの3つのコンポーネントを作成します。実際の開発では、指定したフォルダーにコンポーネントを次のように配置できます。最初のパラメーターが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