寫需求時遇到一個這樣的問題,就是校樣項是多個的,但是其字段名稱相同
這時我們可以這樣校驗,注意字段之間的關聯性
<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-cascaderv-model="item.hospitalDeptRelationId":disabled="!item.hospitalPref"@change="deptChange(item, index)":options="item.deptList":props="deptStrictlyProps"collapse-tagsclearable/></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?字段上,實現動態表單校驗。
可以實現這樣的效果:
?