1

我正在尝试用来Vuelidate控制表单的输入。我为客户的firstname、 the lastname、 thenationality和 the提供了一个输入字段age

在我的应用程序中,有必要检查第一个客户是否至少 18 岁。

我尝试了以下方法来做到这一点:

validations: {
        customers: {
            $each: {
                firstName: { required, minLength: minLength(2), maxLength: maxLength(35) },
                lastName: { required, minLength: minLength(2), maxLength: maxLength(35) },
                nationality: { required }, 
                age: {
                    isFirstCustomerValid: (value) => {
                        return value >= 18
                    }
                }
            }
        }
    }

现在的问题是,这适用于所有非预期的客户。有没有办法只访问 $each 属性的第一个元素?

4

1 回答 1

1

您可以尝试通过 2 种方式查找客户的索引:

  • 如果您的客户具有唯一 ID,请使用:

      const customerIndex = this.customers.findIndex(c => c.id === customer.id)
    
  • 如果没有,你可以尝试使用 lodash 的方法isEqual

    const customerIndex = this.customers.findIndex(c => _.isEqual(c, customer))
    

代码示例:

validations: {
  customers: {
      $each: {
          firstName: { required, minLength: minLength(2), maxLength: maxLength(35) },
          lastName: { required, minLength: minLength(2), maxLength: maxLength(35) },
          nationality: { required }, 
          age: {
              isFirstCustomerValid: (value, customer) => {
                 // if your customer has valid unique id, you can find it by findIndex
                const customerIndex = this.customers.findIndex(c => c.id === customer.id)

                 // OR you ccan try lodash library 'isEqual' method (https://lodash.com/docs/4.17.11#isEqual)
                const customerIndex = this.customers.findIndex(c => _.isEqual(c, customer))

                return customerIndex || value >= 18
              }
          }
      }
  }
}
于 2019-07-05T01:46:08.630 回答