Element ui + Vue表单编辑回显
表单编辑
data.js文件
key表示相对应的字段,el表示类型,然后根据类型来进行判断展示什么组件
const fromRadioList = [
{ label: '是否是新生代企业家', key: 'ifXsdqyj', el: 'radio' },
{ label: '出生年月', key: 'brithDate', el: 'datePicker' },
{
label: '新生代企业家分析',
key: 'xsdqyjFx',
el: 'select',
options: [
{ name: '家族传承', value: 1 },
{ name: '自主创业', value: 2 },
{ name: '创业&传承', value: 3 }
]
},
{
label: '是否为政协委员',
key: 'zxwy',
el: 'input',
isFull: true,
type: 'textarea',
placeholder:
'请填写对应的级别+届数,如县14届政协委员,市15届政协委员(用逗号隔开)'
},
]
export { fromRadioList }
vue文件
<el-form
:model="ruleForm"
:rules="rules"
ref="ruleForm"
:class="$style.ruleForm"
>
<el-form-item
:label="item.label + ':'"
:prop="item.key"
v-for="(item, index) in fromRadioList"
:key="index"
:class="{ [$style.fullX]: item.isFull, [$style.formItem]: true }"
>
<el-input
v-model="ruleForm[item.key]"
:disabled="item.disabled"
:placeholder="item.placeholder ? item.placeholder : '请填写'"
:type="item.type ? item.type : 'text'"
:rows="item.type ? 2 : 1"
v-if="item.el === 'input'"
/>
<el-select
v-model="ruleForm[item.key]"
placeholder="请选择"
v-if="item.el === 'select'"
>
<el-option
v-for="cell in item.options"
:key="cell.name"
:label="cell.name"
:value="cell.value"
/>
</el-select>
<el-radio-group v-model="ruleForm[item.key]" v-if="item.el === 'radio'">
<el-radio :label="1">是</el-radio>
<el-radio :label="0">否</el-radio>
</el-radio-group>
<el-date-picker
v-model="ruleForm[item.key]"
type="month"
placeholder="选择年月"
value-format="yyyy-MM"
format="yyyy-MM"
v-if="item.el === 'datePicker'"
/>
</el-form-item>
</el-form>
<script>
import { fromRadioList } from './data';
data() {
return {
formRadionList, //获取的列表
rules:{}, // 规则
ruleForm:{} // 表单
}
},
created() {
this.fromRadioList.forEach(item => {
const cell = [
{
required: true,
message: '此为必填项,若为空只可保存不可提交',
trigger: 'blur'
}
];
this.$set(this.rules, item.key, cell); //每个必填项挂载到rules上面,
this.$set(this.ruleForm, item.key, '');
});
this.onLoad(); // 请求接口获取表单数据
},
methods:{
onLoad() {
const params = {
id: this.id
};
this.$api['ssqxhx/data-report/getYearDataDel']({ params })
.then(res => {
const { code, data } = res;
if (code === this.$constant.apiServeCode.SUCCESS_CODE) {
for (const key in this.ruleForm) {
this.ruleForm[key] = data[key]; //将表单中需要的字段获取赋值给ruleForm
}
}
return res;
})
.catch(err => {
console.log(err);
});
},
}
</script>
这样就可以不用一个个写item了,直接遍历的写。