问题描述
我有一个动态视图:
<div id="myview">
<div :is="currentComponent"></div>
</div>
带有关联的Vue实例:
with an associated Vue instance:
new Vue ({
data: function () {
return {
currentComponent: 'myComponent',
}
},
}).$mount('#myview');
这允许我动态更改我的组件。
This allows me to change my component dynamically.
就我而言,我有三个不同的组件: myComponent
, myComponent1
和 myComponent2
。我在它们之间切换如下:
In my case, I have three different components: myComponent
, myComponent1
, and myComponent2
. And I switch between them like this:
Vue.component('myComponent', {
template: "<button @click=\"$parent.currentComponent = 'myComponent1'\"></button>"
}
现在,我想将道具传递给 myComponent1
。
Now, I'd like to pass props to myComponent1
.
当我将组件类型更改为 myComponent1
时,如何传递这些道具?
How can I pass these props when I change the component type to myComponent1
?
推荐答案
要动态传递道具,您可以将 v-bind
指令添加到动态组件中,并传递包含道具名称和值的对象:
To pass props dynamically, you can add the v-bind
directive to your dynamic component and pass an object containing your prop names and values:
所以你的动态组件看起来像这样:
So your dynamic component would look like this:
<component :is="currentComponent" v-bind="currentProperties"></component>
在你的Vue实例中, currentProperties
可以根据当前组件进行更改:
And in your Vue instance, currentProperties
can change based on the current component:
data: function () {
return {
currentComponent: 'myComponent',
}
},
computed: {
currentProperties: function() {
if (this.currentComponent === 'myComponent') {
return { foo: 'bar' }
}
}
}
现在,当 currentComponent
是 myComponent
时,它将会有 foo
属性等于'bar'
。如果不是,则不会传递任何属性。
So now, when the currentComponent
is myComponent
, it will have a foo
property equal to 'bar'
. And when it isn't, no properties will be passed.
这篇关于将道具动态传递给VueJS中的动态组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!