我对您的 Codepen on my fork here 做了一些小的修改。你很亲密!
最大的区别在于children 的实现以及我们如何渲染动态组件。
原创
const App = new Vue({
el: '#app',
data: {
componentName: "componentName",
input: "input",
children: [
buttonCounter,
vueHeader
]
},
methods: {
add () {
this.children.push(this.componentName)
},
}
});
修改
const App = new Vue({
el: '#app',
data: {
componentName: "componentName",
input: "input",
children: [
{ componentName: 'button-counter', input: 'I am a button' },
{ componentName: 'vue-header', input: 'I am a header' }
]
},
methods: {
add () {
this.children.push({
componentName: this.componentName,
input: this.input
})
},
}
});
同样,您的模板上的v-for 也会发生变化,以适应children 数组的新形状:
<template v-for="(child, index) in children">
<component :is="child.componentName" :input="child.input" :key="child.name" />
<br>
</template>
因此,如您所见,通过将 children 设为可以接受任何道具的对象数组,您可以将这些相同的道具传递给动态组件。在这种情况下,我们为您的两个自定义组件提供了一个名为 input 的属性,它们被定义为该对象数组的一部分。
需要注意的是,对于 Vue.js 中的动态组件,is 属性可以接受组件本身(例如您的原始方法)或已注册组件的字符串表示。那部分是您的原始叉子和我的叉子之间的主要区别。
hth!