How to get the result of form validation in child element in parent element

1.validate method

The method for validating the entire form, the parameter is a callback function. The callback function will be called after the verification is completed, and pass in two parameters: whether the verification is successful and the field that fails the verification. If no callback function is passed, a promise will be returned.

Note: The validate parameter is a callback function, which is asynchronous. If we want to get the result after verification, we should think of using promsie.

// 父元素
 <Son ref="sonRef"></Son>
 <el-button type="primary" @click="submitForm('numberValidateForm')">提交</el-button>

  async submitForm(){
      let result  = await this.$refs.sonRef.submitForm();
      console.log('返回的值为');
      console.log(result);
      },
// 子元素

<el-form :model="numberValidateForm" ref="numberValidateForm" label-width="100px" class="demo-ruleForm">
        <el-form-item
          label="年龄"
          prop="age"
          :rules="[
            { required: true, message: '年龄不能为空'},
            { type: 'number', message: '年龄必须为数字值'}
          ]"
        >
          <el-input type="age" v-model.number="numberValidateForm.age" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item>
        </el-form-item>
      </el-form>
  submitForm() {
        return new Promise(resolve=>{
            this.$refs['numberValidateForm'].validate(
            (valid) => {
          if (valid) {
            resolve(this.numberValidateForm)
          } else {
           resolve(false)
          }
        });

        })

      },

result:

1. When entering 18,

 2. When the input box is empty:

Guess you like

Origin blog.csdn.net/qq_42931285/article/details/124288117