VueJSで動的なコンポーネントに動的にpropsを渡す

I'動的に見ることができます。

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

と、関連するVueインスタンス。

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

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

私の場合、3つの異なるコンポーネントを持っています。myComponent,myComponent1, そしてmyComponent2` です。そして、このように切り替えて使っている。

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

さて、myComponent1にpropsを渡したいのですが。

コンポーネントタイプを myComponent1 に変更したときに、これらのpropsを渡すにはどうしたらよいでしょうか。

ソリューション

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

つまり、動的コンポーネントは次のようになる。

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

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

これで、currentComponentmyComponent の場合、foo プロパティは 'bar' と等しくなります。そして、そうでないときは、何もプロパティが渡されません。

解説 (6)

また、computed propertyを使わず、オブジェクトをインライン化することも可能です。

<div v-bind="{ id: someProp, 'other-attr': otherProp }"></div>.

V-Bindのドキュメントに表示されています - https://vuejs.org/v2/api/#v-bind

解説 (0)

requireでコードをインポートした場合

var patientDetailsEdit = require('../patient-profile/patient-profile-personal-details-edit')

で、データインスタンスを以下のように初期化します。

data: function () {
            return {
                currentView: patientDetailsEdit,
            }

コンポーネントに name プロパティが割り当てられている場合、name プロパティを通してコンポーネントを参照することもできます。

currentProperties: function() {
                if (this.currentView.name === 'Personal-Details-Edit') {
                    return { mode: 'create' }
                }
            }
解説 (0)