Vue 有一种非常简单的生成动态组件的方法:
<component :is="dynamicComponentName"></component>
所以我建议你将选项定义为数组并将类型设置为组件名称:
options: [
{
type: 'FormInput',
propsData: {label: 'Name'}
},
{
type: 'FormButton',
propsData: {label: 'Send'}
}
]
然后在表单生成器中使用它,如下所示:
<component :is="option.type" v-for="option in options"></component>
您还可以像传递给其他组件一样传递属性,但由于它是动态的并且每个组件都有一组不同的属性,因此我会将其作为对象传递,每个组件将访问它需要的数据:
<component :is="option.type" v-for="option in options" :data="option.propsData"></component>
UPDATE
由于您无法控制组件,因此需要更多操作:
对于每个需要文本的组件,在选项中添加文本属性:
options: [
{
type: 'FormInput',
propsData: {label: 'Name'}
},
{
type: 'FormButton',
text: 'Send',
propsData: {label: 'Send'}
}
]
然后在组件中使用它:
<component :is="option.type" v-for="option in options">{{option.text}}</component>
对于传递属性,我认为你可以使用 v-bind 传递它,然后它会自动解构它们,所以如果一个按钮接受 2 个属性:rounded, color
选项如下所示:
{
type: 'FormButton',
text: 'Button',
propsData: {rounded: true, color: '#bada55'}
}
然后是组件:
<component :is="option.type" v-for="option in options" v-bind="option.propsData">{{option.text}}</component>