element ui表單校驗prop的鏈式寫法----源碼分析


<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數組的第一個元素

附上部分源碼

 

 好啦,這次對表單校驗的這種寫法可以理解了吧!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM