通过范围Vee验证validateAll()

Nev*_*e12 5 javascript promise vue.js vee-validate

我有一种情况,我已经将表单切成段(范围),以便可以使用以下函数一次验证小块。

validateScope (scope) {
  return this.$validator.validateAll(scope);
}
Run Code Online (Sandbox Code Playgroud)

我想对整个表单进行一次最终验证,然后再将其提交给服务器。但是,validateAll()似乎没有拾取已添加到作用域的输入。我还尝试过验证每个范围,然后提交表单(如果它们全部有效),但是由于所有都是异步的,因此我不确定如何执行此操作。

validateAll () {
   let valid = true;

   // Not sure how to build this function since validateScope is asynchronous
   _.each(this.names, (name, index) => {
     if(this.validateScope('name-' + index)){
       valid = false;
     }
   });

   return valid; // Always returns true even though the _.each should set it to false
}
Run Code Online (Sandbox Code Playgroud)

Ber*_*ert 6

正如我在评论中提到的,您的代码最终将看起来像这样:

validateAll () {
   let valid = true;

   let validations = []
   _.each(this.names, (name, index) => {
     validations.push(this.validateScope('name-' + index))
   });

   return Promise.all(validations)
     // consolidate the results into one Boolean
     .then(results => results.every(r => r))
}
Run Code Online (Sandbox Code Playgroud)

然后,当然,您必须将其validateAll用作承诺:

this.validateAll().then(isValid => {
  if (!isValid) {
    //do whatever you need to do when something failed validation
  } else {
    // do whatever you need to do when everything is valid here
  }
})
Run Code Online (Sandbox Code Playgroud)