写需求时遇到一个这样的问题,就是校样项是多个的,但是其字段名称相同
这时我们可以这样校验,注意字段之间的关联性
<div v-for="(item,index) in formData.hospitalDoctorList" :key="item.key || index">
<el-form-item label="科室"
:prop="'hospitalDoctorList.' + index + '.hospitalDeptRelationId'"
:rules="[{ required: true, message: '请选择医生在此医院的科室'
, trigger:['change','blur'] }]">
<el-cascader
v-model="item.hospitalDeptRelationId"
:disabled="!item.hospitalPref"
@change="deptChange(item, index)"
:options="item.deptList"
:props="deptStrictlyProps"
collapse-tags
clearable
/>
</el-form-item>
在 el-form-item 组件中,:prop 属性用于指定该表单项对应的校验字段路径。
这里的写法是字符串拼接,最终会生成类似 hospitalDoctorList.0.hospitalDeptRelationId、hospitalDoctorList.1.hospitalDeptRelationId 这样的路径。
- hospitalDoctorList 是一个数组,里面存放着多个医生(或药师)的信息对象。
- index 是当前循环的索引(比如 0、1、2...),通常在 v-for 循环中传入。
- hospitalDeptRelationId 是每个医生(药师)对象中的一个字段,表示“药师id”。
所以,:prop="'hospitalDoctorList.' + index + '.hospitalDeptRelationId'"
就是告诉表单校验系统:当前这个表单项对应的数据字段是 hospitalDoctorList 数组中第 index 个对象的 hospitalDeptRelationId 字段。
这样做的好处是,表单校验(比如 required 校验)可以精确地作用到每个医生(药师)对象的 hospitalDeptRelationId 字段上,实现动态表单校验。
可以实现这样的效果: