简体   繁体   English

如何使用 vee-validate 验证所有引用?

[英]how to validate all refs with vee-validate?

I have dynamic components that needs to be validated.我有需要验证的动态组件。

I have an array and i push my components there.我有一个数组,我把我的组件推到那里。 The for loop works great. for 循环效果很好。

    validateForm() {
      const PROMISES = [this.$refs.contactDetailsForm.$refs.contactDetails]
      for (let i = 1; i <= this.count; i++) {
        PROMISES.push(this.$refs[`passengerForm${i}`][0])
      }


      return Promise.all(PROMISES)
    },

But problem is I do not know how to return the results of the validation.但问题是我不知道如何返回验证结果。 I want the results of this function in another function(Promise).我想在另一个函数(Promise)中得到这个函数的结果。 how can I do that?我怎样才能做到这一点?

this is the solution:这是解决方案:

    validateForm() {
      const PROMISES = [this.$refs.contactDetailsForm.$refs.contactDetails]
      for (let i = 1; i <= this.count; i++) {
        PROMISES.push(this.$refs[`passengerForm${i}`][0])
      }

      return new Promise((resolve, reject) => {
        PROMISES.forEach(async (item) => {
          const STATUS = await item.validate()
          STATUS ? resolve(STATUS) : reject(STATUS)
        })
      })
    }

Untested, but Promise.all returns an array of results for the promises.未经测试,但 Promise.all 返回承诺的结果数组。 What you need to do is trigger validate for all the things you want to know the result for, collect those promises and then check the results in a Promise.all.你需要做的是为所有你想知道结果的事情触发验证,收集这些承诺,然后在 Promise.all 中检查结果。 You didn't give quite enough code to answer this fully but it's something like this:你没有提供足够的代码来完全回答这个问题,但它是这样的:

validateForm() {
  //both of these I added validate() to because I'm hoping they are references to ValidationObservers
  const PROMISES = [this.$refs.contactDetailsForm.$refs.contactDetails.validate()]
  for (let i = 1; i <= this.count; i++) {
    PROMISES.push(this.$refs[`passengerForm${i}`][0].validate())
  }

  return Promise.all(Promises);
}

Then wherever you are calling this, you'd do:然后无论你在哪里调用它,你都会这样做:

this.validateForm().then((values) => {
    this.formIsValid = values.every((result) => result));
    //if the things above are ValidationProviders rather than VO, you have to use result.valid instead of result
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM