问题描述
我有一个动态视图:
<div :is="currentComponent"></div>
具有关联的 Vue 实例:
新的 Vue ({数据:函数(){返回 {当前组件:'我的组件',}},}).$mount('#myview');
这允许我动态更改我的组件.
就我而言,我有三个不同的组件:myComponent
、myComponent1
和 myComponent2
.我像这样在它们之间切换:
Vue.component('myComponent', {模板:<button @click="$parent.currentComponent = 'myComponent1'"></button>"}
现在,我想将 props 传递给 myComponent1
.
当我将组件类型更改为 myComponent1
时,如何传递这些 props?
要动态传递 props,您可以将 v-bind
指令添加到您的动态组件并传递一个包含您的 prop 名称和值:
因此您的动态组件将如下所示:
并且在您的 Vue 实例中,currentProperties
可以根据当前组件进行更改:
数据:函数(){返回 {当前组件:'我的组件',}},计算:{当前属性:函数(){if (this.currentComponent === 'myComponent') {返回 { foo: 'bar' }}}}
所以现在,当 currentComponent
是 myComponent
时,它将有一个 foo
属性等于 'bar'
.如果不是,则不会传递任何属性.
I've a dynamic view:
<div id="myview">
<div :is="currentComponent"></div>
</div>
with an associated Vue instance:
new Vue ({
data: function () {
return {
currentComponent: 'myComponent',
}
},
}).$mount('#myview');
This allows me to change my component dynamically.
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>"
}
Now, I'd like to pass props to myComponent1
.
How can I pass these props when I change the component type to myComponent1
?
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>
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' }
}
}
}
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.
这篇关于将 props 动态传递给 VueJS 中的动态组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!