我正在制作一个表单生成器,它使用它的输入字段,按钮等组件。我希望能够生成的表单取决于我传递给它的选项。
但是我不能让它来渲染组件。
我试图返回纯HTML,但这不会呈现组件。
我从我的Home.vue模板调用表单生成器,其中我希望表单具有如下的options对象:
options: {
name: {
type: 'input',
label: 'Name'
},
submit: {
type: 'button',
label: 'Send'
}
}在模板中:
<template>
<form-generator :options="options"></form-generator>
</template>在表单生成器组件中,我尝试了多种方法,例如:
<template>
{{ generateForm(this.options) }}
// ... or ...
<div v-html="generateForm(this.options)"></div>
</template>我包含了所有的组件,比如:
import {
FormButton,
FormInput
} from './FormComponents'现在最后一部分是如何让FormInput渲染?
这不起作用,因为它逐字输出HTML:
methods: {
generateForm(options) {
// .. do stuff with options ..
var form = '<form-input />'
return form
}
}发布于 2017-10-08 20:40:19
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>更新
由于您无法控制组件,因此需要更多的操作:
对于每个需要文本的组件,请在选项中添加文本属性:
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个props: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>发布于 2020-08-26 03:01:35
您可以像这样创建数组:
components_data: [
{
name: 'checkbox',
data: false
},
{
name: 'text',
data: 'Hello world!'
}
]然后在<component>内部遍历这个数组
<component
v-for="(component,i) in components_data"
:key="i"
:is="component.name"
:data="component.data"
/>这将动态创建2个组件[<text>, <checkbox>],并通过属性为它们提供数据。
当您推送像这样的新数据时,它会将一个新组件呈现为<image :data="{url:'cat.jpg'}"/>
发布于 2017-10-08 20:39:39
您可以遍历模板中的选项并检查选项类型:
<template>
<div v-for="option in options">
<form-input v-if="option.type === 'input'"></form-input>
<form-button v-else-if="option.type === 'button'"></form-button>
</div>
</template>https://stackoverflow.com/questions/46631134
复制相似问题