使用 VeeValidate,我如何查看某个字段是否已被触摸并且是否有效?

With VeeValidate, how can I see if a field has been touched and is valid?

我正在尝试从计算的 prop 访问验证标志:

computed: {
  isFormValid() {
    let isValid = this.$validator.fields.some(field => {
      console.log(field.flags);
      return field.flags.touched; || field.flags.invalid;
    });
    console.log("isValid", isValid);
    return isValid;
  }
},

但这给出了一个错误:"TypeError: this.$validator.fields.some is not a function"

然后我想我会遍历 observable:

let isValid = Array.from(this.$validator.fields).some(field => {
  console.log(field.flags);
  return field.flags.touched; //|| field.flags.invalid;
});

耶!进步!没有更多的错误。但是当我更改表单输入值时它不会重新计算。

那我该怎么做呢?

v2 docs show an example that iterates this.fields (instead of this.$validator.fields) via Object.keys:

// MyComponent.vue
export default {
  // ...
  computed: {
    isFormDirty() {
      return Object.keys(this.fields).some(key => this.fields[key].dirty);
    }
  },
  //...
}

使用该示例,您的计算道具将是:

// MyComponent.vue
export default {
  // ...
  computed: {
    isFormTouchedOrInvalid() {
      return Object.keys(this.fields).some(key => this.fields[key].touched || this.fields[key].invalid);
    }
  },
  //...
}

v2 demo

在 v3 中,您可以use the <ValidationProvider> component轻松访问模板中的验证标志:

<ValidationProvider rules="required" v-slot="{ touched, invalid }">
  <pre>touched:{{touched}} invalid:{{invalid}}</pre>
  <input type="email" v-model="value">
</ValidationProvider>

v3 demo