1. 程式人生 > 實用技巧 >element ui中動態新增的表單進行驗證

element ui中動態新增的表單進行驗證

專案中有一項表單是需要動態新增的,但是動態新增的表單,驗證規則也需要動態新增。

官網中的例子:

程式碼如下:

注意事項在程式碼中紅色註釋

<el-form :model="dynamicValidateForm" ref="dynamicValidateForm" label-width="100px" class="demo-dynamic"> //這裡的model一定要用 :model 形式 而不是 v-model
  <el-form-item
    prop="email"
    label="郵箱"
    :rules="[
      { required: true, message: '請輸入郵箱地址', trigger: 'blur' },
      { type: 'email', message: '請輸入正確的郵箱地址', trigger: ['blur', 'change'] }
    ]
" > <el-input v-model="dynamicValidateForm.email"></el-input> </el-form-item> <el-form-item v-for="(domain, index) in dynamicValidateForm.domains" :label="'域名' + index" :key="domain.key" :prop="'domains.' + index + '.value'" //這裡的prop繫結的時候一定要從你v-for迴圈下的物件中。 prop屬性後面也就是你要驗證的地方。
: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: '' }], email: '' } }; }, 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>

具體可參考官網:https://element.eleme.cn/#/zh-CN/component/form