背景:朋友入职新公司,做项目重构,根据后端返回表单内容,动态生成表单,于是自己实现了下,哪里写的不好,欢迎各位提建议:文章来源:https://www.toymoban.com/news/detail-507718.html
因为开关和多选框默认值是非空字符串,所以在created生命周期单独处理了下文章来源地址https://www.toymoban.com/news/detail-507718.html
<template>
<div class="home">
<el-form ref="form" :model="form" label-width="80px">
<el-form-item v-for="(item,index) in list" :key="index" :label="item.label">
<el-input v-if="item.type === 'input'" v-model="form[item.key]"></el-input>
<el-select v-if="item.type === 'select'" v-model="form[item.key]" placeholder="请选择活动区域">
<el-option v-for="element in item.select" :key="element.label" :label="element.label" :value="element.value"></el-option>
</el-select>
<el-date-picker v-if="item.type === 'date-picker'" type="date" placeholder="选择日期" v-model="form[item.key]" style="width: 100%;"></el-date-picker>
<el-switch v-if="item.type === 'switch'" v-model="form[item.key]"></el-switch>
<el-checkbox-group v-if="item.type === 'checkbox-group'" v-model="form[item.key]">
<el-checkbox v-for="element in item.select" :key="element.label" :label="element.label" name="type"></el-checkbox>
</el-checkbox-group>
<el-radio-group v-if="item.type === 'radio-group'" v-model="form[item.key]">
<el-radio v-for="element in item.select" :key="element.label" :label="element.label"></el-radio>
</el-radio-group>
<el-input v-if="item.type === 'textarea'" type="textarea" v-model="form[item.key]"></el-input>
</el-form-item>
</el-form>
</div>
</template>
<script>
export default {
name: "Home",
components: {
},
data() {
return {
form: {
},
list: [
{
label: "xxx",
type: "input",
key: "key1",
},
{
label: "xxx",
type: "date-picker",
key: "key2",
},
{
label: "xxx",
type: "select",
key: "key3",
select: [
{
label: "下拉框1",
value: "1",
},
{
label: "下拉框2",
value: "2",
},
],
},
{
label: "xxx",
type: "switch",
key: "key4",
},
{
label: "xxx",
type: "checkbox-group",
key: "key5",
select: [
{
label: "下拉框1",
value: "1",
},
{
label: "下拉框2",
value: "2",
},
],
},
{
label: "xxx",
type: "radio-group",
key: "key6",
select: [
{
label: "下拉框1",
value: "1",
},
{
label: "下拉框2",
value: "2",
},
],
},
{
label: "xxx",
type: "textarea",
key: "key7",
}
],
};
},
created () {
const form = {}
this.list.forEach(item => {
if (item.type === 'checkbox-group') {
form[item.key] = []
} else if (item.type === 'switch') {
form[item.key] = false
}
})
this.form = form
}
}
</script>
到了这里,关于element-ui 动态表单的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!