最近有个新的业务、主要涉及多层级的动态表单提交,其中又涉及很多类型,踩了很多坑之后,终于研发完毕。
传来的数据格式涉及比较多的内容,以下举例一个,涉及到规则的填写
规则写法有两种,一种是直接在表单里添加规则,一种是在字段中添加规则
我这里字段的定义是因为有其他数据要一并提交,可按照自己需求来
1、字段里label-width我设定的是300,是因为会有比较长的字段。根据返回文本,自行调节
2、:name字段主要是为了寻找key值,这个必填,
dynamicLists为数组,index为数组下标位置,value
<uni-forms ref="dynamicForm" :modelValue="dynamicFormData" label-position="top" label-width="300px">
<view v-for="(item, index) in dynamicFormData.dynamicLists" :key="item.inspectionItemId">
<uni-forms-item :label="index+1+'.'+ide+1+'、'+ite.itemName" label-width="100%"
:rules="[{required: true,errorMessage: '请填写'}]"
:name="['dynamicLists',index,'value']" required>
<uni-data-checkbox v-model="dynamicFormData.dynamicLists[index].value"
:localdata="ite.itemValueList" />
</uni-forms-item>
</view>
</uni-forms>
<script>
export default {
data(){
return{
dynamicFormData:{
dynamicLists:[],
}
}
}
}
</script>
首先要对数据处理
在数据里添加rules规则
rules: [{
'required': true,
errorMessage: "请填写" + this.detail[i].itemName//这里写你想校验的内容
}],
this.detail是我从后台返回的数据,其中内容做了处理。按照自己的值编辑
this.dynamicFormData.dynamicLists.push({
label: this.detail[i].itemName,
value: "",
itemType: this.detail[i].itemType,
rules: [{
'required': true,
errorMessage: "请填写" + this.detail[i].itemName
}],
inspectionId: this.detail[i].inspectionId,
itemValueList: itemValueList,
children: children,
includeImage: this.detail[i].includeImage,
})
<uni-forms-item :label="index+1+'.'+ide+1+'、'+ite.itemName" label-width="100%"
:rules="item.rules"
:name="['dynamicLists',index,'value']" required>
<uni-data-checkbox v-model="dynamicFormData.dynamicLists[index].value"
:localdata="ite.itemValueList" />
</uni-forms-item>
子级的表单与父级一致,主要添加了以下字段
<uni-forms-item :label="index+1+'.'+ide+1+'、'+ite.itemName" label-width="100%"
:rules="[{required: true,errorMessage: '请填写'}]"
:name="['dynamicLists',index,'value']" required>
<uni-data-checkbox v-model="dynamicFormData.dynamicLists[index].value"
:localdata="ite.itemValueList" />
</uni-forms-item>
<uni-forms-item :label="index+1+'.'+ide+1+'、'+ite.itemName" required
:rules="ite.rules"
:name="['dynamicLists',index,'children',ide,'value']">
<uni-easyinput class="easyinput" trim="all" :autoHeight="true"
maxlength="500"type="textarea"
v-model="dynamicFormData.dynamicLists[index].children[ide].value"
placeholder="请输入内容" />
</uni-forms-item>
编辑完毕
图例1、验证不通过,未填写
图例2、填写数据、校验规则消失