VueJS の動的コンポーネントにプロパティを動的に渡す 質問する

VueJS の動的コンポーネントにプロパティを動的に渡す 質問する

私はダイナミックな視点を持っています:

<div id="myview">
  <div :is="currentComponent"></div>
</div>

関連する Vue インスタンス:

new Vue ({
  data: function () {
    return {
      currentComponent: 'myComponent',
    }
  },
}).$mount('#myview');

これにより、コンポーネントを動的に変更できるようになります。

私の場合、myComponentmyComponent1、という 3 つの異なるコンポーネントがあります。myComponent2そして、それらを次のように切り替えます。

Vue.component('myComponent', {
  template: "<button @click=\"$parent.currentComponent = 'myComponent1'\"></button>"
}

ここで、 props を に渡したいと思いますmyComponent1

コンポーネント タイプを に変更するときに、これらのプロパティを渡すにはどうすればよいですかmyComponent1?

ベストアンサー1

プロパティを動的に渡すには、v-bind動的コンポーネントにディレクティブを追加し、プロパティの名前と値を含むオブジェクトを渡します。

したがって、動的コンポーネントは次のようになります。

<component :is="currentComponent" v-bind="currentProperties"></component>

Vue インスタンスでは、currentProperties現在のコンポーネントに基づいて変更できます。

data: function () {
  return {
    currentComponent: 'myComponent',
  }
},
computed: {
  currentProperties: function() {
    if (this.currentComponent === 'myComponent') {
      return { foo: 'bar' }
    }
  }
}   

したがって、 がcurrentComponentの場合、に等しいプロパティmyComponentを持つことになります。 そうでない場合は、プロパティは渡されません。foo'bar'

おすすめ記事