我有一个动态 View :
<div id="myview">
<div :is="currentComponent"></div>
</div>
与关联的 Vue 实例:
new Vue ({
data: function () {
return {
currentComponent: 'myComponent',
}
},
}).$mount('#myview');
这允许我动态更改我的组件。
在我的例子中,我有三个不同的组件:myComponent
、myComponent1
和 myComponent2
。我像这样在它们之间切换:
Vue.component('myComponent', {
template: "<button @click=\"$parent.currentComponent = 'myComponent1'\"></button>"
}
现在,我想将 props 传递给 myComponent1
。
当我将组件类型更改为 myComponent1
时,如何传递这些 props?
最佳答案
要动态传递 props,您可以将 v-bind
指令添加到您的动态组件并传递一个包含您的 prop 名称和值的对象:
所以你的动态组件看起来像这样:
<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'
。如果不是,则不会传递任何属性。
关于javascript - 将 Prop 动态传递给 VueJS 中的动态组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43658481/