首页 > 解决方案 > Vue.js - Element UI - 获取表单验证的状态

问题描述

在此处输入图像描述

重现步骤

重复链接是这样的:https ://stackblitz.com/edit/typescript-vuejs-element-3kko7a

password input 2

username input 11

Change username to 2// should be able to submit, but not

预期: formvalid = true

在此处验证代码:

 checkForm() {
        // console.log('validate runs');
        // @ts-ignore
        const fields = this.$refs.ruleForm.fields;
        if (fields.find((f) => f.validateState === 'validating')) {
          setTimeout(() => {
            this.checkForm();
          }, 100);
        }
        this.formValid = fields.reduce((acc, f) => {
          const valid = (f.isRequired && f.validateState === 'success');
          const notErroring = (!f.isRequired && f.validateState !== 'error');
          return acc && (valid || notErroring);
        }, true);
        console.log('valid:', this.$data.formValid);
      }

标签: vue.jsvuejs2element-ui

解决方案


基本上你看ruleForm- 所以每次ruleForm更改你都会触发checkform- 但是你的验证器会在blur你设置后触发,ruleForm所以你首先测试然后变为有效。将其更改为吸气剂:

get formValid(){

   const fields = this.$refs.ruleForm.fields || [];
    if (fields.find((f) => f.validateState === 'validating')) {
      setTimeout(() => {
        this.checkForm();
      }, 100);
    }
    return fields.reduce((acc, f) => {
      const valid = (f.isRequired && f.validateState === 'success');
      const notErroring = (!f.isRequired && f.validateState !== 'error');
      return acc && (valid || notErroring);
    }, fields.length > 0);
} 

推荐阅读