<el-form :model="dynamicValidateForm" ref="dynamicValidateForm" label-width="100px" class="demo-dynamic"> <el-form-item v-for="(domain, index) in dynamicValidateForm.domains" :label="'域名' + index" :key="domain.key" :prop="'domains.' + index + '.value'" :rules="{ required: true, message: '域名不能為空', trigger: 'blur' }" > <el-input v-model="domain.value"></el-input><el-button @click.prevent="removeDomain(domain)">刪除</el-button> </el-form-item> <el-form-item> <el-button type="primary" @click="submitForm('dynamicValidateForm')">提交</el-button> <el-button @click="addDomain">新增域名</el-button> <el-button @click="resetForm('dynamicValidateForm')">重置</el-button> </el-form-item> </el-form> <script> export default { data() { return { dynamicValidateForm: { domains: [{ value: '' }] } }; }, methods: { submitForm(formName) { this.$refs[formName].validate((valid) => { if (valid) { alert('submit!'); } else { console.log('error submit!!'); return false; } }); }, resetForm(formName) { this.$refs[formName].resetFields(); }, removeDomain(item) { var index = this.dynamicValidateForm.domains.indexOf(item) if (index !== -1) { this.dynamicValidateForm.domains.splice(index, 1) } }, addDomain() { this.dynamicValidateForm.domains.push({ value: '', key: Date.now() }); } } } </script>
其中動態表單校驗中用到了:prop="'domains.' + index + '.value'" 而domains 是一個數組。 常規來說這么寫相當於是 domains.1.value 的寫法,但這種寫法肯定是有問題的。沒看源碼不是很理解這樣的鏈式操作。
感覺:prop="'domains.' + index + '.value'" 這種寫法錯誤的 會換成 :prop="'domains[' + index + '].value'" 這種寫法, 其實看了源碼之后才明白 這兩種寫法都是正確的
1 . prop 接收的數據類型是String ,
2. :prop="'domains.' + index + '.value'" 和 :prop="'domains[' + index + '].value'" 這兩種傳值最終都是轉換成了 domains.0.value 字符串,這是一個字符串 而不是通過 domains.0 來取domains數組的第一個元素
附上部分源碼
好啦,這次對表單校驗的這種寫法可以理解了吧!