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を渡すにはどうしたらよいでしょうか。
72
3
プロップを動的に渡すには、
v-bind
ディレクティブをダイナミックコンポーネントに追加して、プロップの名前と値を含むオブジェクトを渡します。つまり、動的コンポーネントは次のようになる。
そして、Vueインスタンスでは、
currentProperties
は現在のコンポーネントに基づいて変更することができます。これで、
currentComponent
がmyComponent
の場合、foo
プロパティは'bar'
と等しくなります。そして、そうでないときは、何もプロパティが渡されません。また、computed propertyを使わず、オブジェクトをインライン化することも可能です。
<div v-bind="{ id: someProp, 'other-attr': otherProp }"></div>
.V-Bindのドキュメントに表示されています - https://vuejs.org/v2/api/#v-bind
requireでコードをインポートした場合
で、データインスタンスを以下のように初期化します。
コンポーネントに name プロパティが割り当てられている場合、name プロパティを通してコンポーネントを参照することもできます。