计算属性的验证验证

H M*_*ail 1 vue.js vuelidate

在我的 Vue 组件中,我有 3 个数字字段,如下所示:

data() {
    return {
        numberAdults: 0,
        numberChildren: 0,
        numberInfants: 0,
    }
Run Code Online (Sandbox Code Playgroud)

还有一个计算属性:

computed: {
    numberPersons() {
        return this.numberAdults + this.numberChildren + this.numberInfants
    },
Run Code Online (Sandbox Code Playgroud)

我想验证至少设置了一个人(至少一名成人或一名儿童或一名婴儿),但我无法使其发挥作用。这是验证规则:

numberPersons: {
    required,
    minValue: minValue(1),
},
Run Code Online (Sandbox Code Playgroud)

如果我更改numberPersons三个字段之一,则该字段的验证有效。我认为 Vuelidate 不知何故不知道是什么numberPersons,但我不知道如何改变它。

Ter*_*rry 7

您可以创建一个自定义验证方法,例如,minNumberPersons简单地验证您的计算属性this.numberPersons

const minNumberPersons = (value, vm) => {
    return vm.numberPersons >= 1;
};
Run Code Online (Sandbox Code Playgroud)

然后,您可以将这些规则应用于不同的模型:

validations: {
  numberAdults: { numberPersons },
  numberChildren: { numberPersons },
  numberInfants: { numberPersons }
}
Run Code Online (Sandbox Code Playgroud)

UX 建议,完全可选:附带说明,由于您将同时验证 3 个字段,因此使用该$v.<field>.$touch()方法确保所有 3 个字段的脏状态设置为true当它们中的任何一个时是有意义的改变了。您可以简单地@input="onInput"在模板中进行绑定,并将其添加到您的方法中:

onInput() {
  this.$v.numberAdults.$touch();
  this.$v.numberChildren.$touch();
  this.$v.numberInfants.$touch();
},
Run Code Online (Sandbox Code Playgroud)

请参阅此处的概念验证。我从Vuelidate 存储库使用演示 JSFiddle 中改编了它。

const minNumberPersons = (value, vm) => {
    return vm.numberPersons >= 1;
};
Run Code Online (Sandbox Code Playgroud)
validations: {
  numberAdults: { numberPersons },
  numberChildren: { numberPersons },
  numberInfants: { numberPersons }
}
Run Code Online (Sandbox Code Playgroud)
onInput() {
  this.$v.numberAdults.$touch();
  this.$v.numberChildren.$touch();
  this.$v.numberInfants.$touch();
},
Run Code Online (Sandbox Code Playgroud)