动态生成的表单,绑定表单校验
需求获取记录并支持修改 并进行表单验证
- 创建rules 和 from表单 绑定 from的:model 和 rules 即可
1.1 创建rules
return {
ruleForm:[
{
xm: '',
dw: '',
dh: ''
},
{
xm: '',
dw: '',
dh: ''
}
],
rules: {
xm: [
{required: true, message: '请输如姓名', trigger: 'blur'},
],
dw: [
{required: true, message: '请输入单位', trigger: 'blur'},
],
dh: [
{required: true, message: '请输入电话', trigger: 'blur'},
]
}
};
},
1.2 创建form表单
<el-form style="height: 744px;overflow-y: scroll" :model="ruleForm" :rules="rules" ref="ruleForm">
<div v-for="(item,index) in ruleForm" :key="index">
<el-row >
<el-col :span="span">
<el-form-item label="姓名:" label-width="35%" :prop="index+'.'+'xm'" :rules="rules.xm">
<el-input v-model="item.xm"></el-input>
</el-form-item>
</el-col>
<el-col :span="span">
<el-form-item label="单位:" label-width="30%" :prop="index+'.'+'dw'" :rules="rules.dw">
<el-input v-model="item.dw"></el-input>
</el-form-item>
</el-col>
<el-col :span="span" >
<el-form-item label="电话:" label-width="30%" :prop="index+'.'+'dh'" :rules="rules.dh">
<el-input v-model="item.dh" style="width:100%"></el-input>
</el-form-item>
</el-col>
</el-row>
</div >
</el-form>
- 验证
this.$refs[ruleForm].validate((valid) => {
if (valid) {
alert('submit!');
} else {
console.log('error submit!!');
return false;
}
});
效果如下:
ps: 如果 ruleForm是单个对象 用以下方式绑定
:prop="‘ruleForm.’ + index + ‘.’ + index2"