赞
踩
背景:朋友入职新公司,做项目重构,根据后端返回表单内容,动态生成表单,于是自己实现了下,哪里写的不好,欢迎各位提建议:
因为开关和多选框默认值是非空字符串,所以在created生命周期单独处理了下
<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>
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。