element ui 官網 Form組件提供了一個動態增加表單項及驗證的demo,但其過於簡單,以至於網上存在很多動態增加表單項,無法正確驗證的問題,按官網方法嘗試多次無效后,果斷甩開官方寫法,完全換一種方式實現,代碼如下:
<el-form :model="dynamicForm" ref="dynamicValidateForm" label-width="140px" class="demo-dynamic"> <div v-for="(item) in dynamicValidateForm.field" :key="item.rnd" class="new-item"> <el-row style="text-align:right"> <span class="ryDelete" @click="handleThisItem(item)">刪除</span> </el-row> <el-form-item :label="'榮譽名稱' + item.rnd" :prop="'honor' + (item.rnd)" :rules="[{required: true, message: '名稱不能為空', trigger: 'blur'}, {validator: checkAge}]"> <el-input v-model="dynamicForm[`honor${item.rnd}`]"></el-input> </el-form-item> <el-form-item :label="'簽到時間' + item.rnd" :prop="'time' + (item.rnd)" :rules="[{required: true, message: '時間不能為空', trigger: 'blur'}]"> <el-input v-model="dynamicForm[`time${item.rnd}`]"></el-input> </el-form-item> <el-form-item :label="'頒發部門' + item.rnd" :prop="'depart' + (item.rnd)" :rules="[{required: true, message: '部門不能為空', trigger: 'blur'}]"> <el-input v-model="dynamicForm[`depart${item.rnd}`]"></el-input> </el-form-item> </div> <el-row> <el-col :span="24"> <el-button type="plain" @click="addDomain">新增榮譽</el-button> <el-button type="plain" @click="saveHonor">保存榮譽</el-button> </el-col> </el-row> </el-form>
data () { const checkAge = (rule, value, callback) => { console.log('custom') if (!value) { return callback(new Error('年齡不能為空')) } setTimeout(() => { if (!Number.isInteger(value)) { callback(new Error('請輸入數字值')) } else { if (value < 18) { callback(new Error('必須年滿18歲')) } else { callback() } } }, 1000) } return { radio: '1', name: 0, dynamicValidateForm: { field: [] }, dynamicForm: {}, checkAge: checkAge } }, created () { this.addDomain() }, methods: { addDomain () { const rnd = Math.floor(Math.random() * 1000000) this.dynamicValidateForm.field.push({ rnd }) const honorName = 'honor' + rnd const timeName = 'time' + rnd const departName = 'depart' + rnd this.$set(this.dynamicForm, honorName) this.$set(this.dynamicForm, timeName) this.$set(this.dynamicForm, departName) }, saveHonor () { const ret = [] this.dynamicValidateForm.field.forEach(item => { ret.push({ honor: this.dynamicForm[`honor${item.rnd}`], time: this.dynamicForm[`time${item.rnd}`], depart: this.dynamicForm[`depart${item.rnd}`] }) }) console.log('ret', ret) }, handleThisItem (obj) { let index = -1 this.dynamicValidateForm.field.forEach((item, i) => { if (item.rnd === obj.rnd) { index = i } }) this.dynamicValidateForm.field.splice(index, 1) this.$delete(this.dynamicForm, `honor${obj.rnd}`) this.$delete(this.dynamicForm, `time${obj.rnd}`) this.$delete(this.dynamicForm, `depart${obj.rnd}`) }, }
官網增減表單項采用的是對象嵌套數組的方法,這樣雖然方便,但驗證寫法及其麻煩
本demo可以直接使用,簡單擴充字段即可