需求:有个表单信息是v-for渲染的,例如下图,通过循环遍历实现新增和删除模块,按照平时的写法实现校验,是不能实现我们想要的效果,根据这个需求,我找到了一个解决方法
1.HTML
<el-form ref="form" :model="form" :rules="rules" label-width="110px" ><div v-for="(item,index) in this.form.trucksList"><div class="num">{{index+1}}.</div><div class="flex"><div class="info"><el-form-item label="服务商" :prop="'trucksList.' + index+'.providerType'" :rules="rules.providerType"><el-select v-model="item.providerType" placeholder="请选择"><el-optionv-for="item in options":key="item.value":label="item.label":value="item.label"></el-option></el-select></el-form-item><el-form-item label="卡车公司" :prop="'trucksList.' + index+'.truckCompany'" :rules="rules.truckCompany"><el-inputv-model="item.truckCompany"placeholder="请输入卡车公司"/></el-form-item><el-form-item label="预估运输时间" :prop="'trucksList.' + index+'.transportDay'" :rules="rules.transportDay"><el-inputv-model="item.transportDay "placeholder="请输入预估运输时间"/></el-form-item><el-form-item label="总价" :prop="'trucksList.' + index+'.priceTotal'" :rules="rules.priceTotal"><el-inputv-model="item.priceTotal "placeholder="请输入总价"/></el-form-item></div></div></div>
</el-form>
2.JS
data(){return{// 报价表单参数form: {trucksList:[{providerType:'',//服务商truckCompany:'',//卡车公司transportDay:'',//预估运输时间priceTotal:'',//总价orderNo:" ",//平台订单号}],},// 表单校验rules:{providerType:[{ required: true, message: "请选择服务商", trigger: "blur" }],truckCompany:[{ required: true, message: "请输入卡车公司", trigger: "blur" }],transportDay:[{ required: true, message: "请输入预估运输时间", trigger: "blur" }],priceTotal:[{ required: true, message: "请输入总价", trigger: "blur" }], },}},
注:
1.循环的数据中,每个el-form-item都写rules、prop
2.rules为data中rules对象对应属性,如'rules.providerType';
3.prop的第一部分为data中该组遍历数据对应的数组名,此例中为form中的'trucksList';第二部分为遍历的key值变量;第三部分为form中的'trucksList'中该输入框对应的属性名;
只有以上几点写对,就可以实现循环数据的表单校验啦