vue uses Promise.all for multi-form validation

Preface

  • In the development of the project, you will inevitably encounter form validation. If your project has many forms on an interface, you will need to write each form to verify the form. The repeated code will look bloated. Here we will use the method to solve this problem Promise.all().

Promise.all() method

  • Promise.all()Methods provide the ability to execute asynchronous operations in parallel and execute callbacks only after all asynchronous operations have been executed. Multiple instances can be Promisepackaged into a new Promiseinstance

Implement multiple form validation

  • First we have to write a verification method, and then put the form loop that needs to be verified into Promise.allit through thenthe callback function, and then write the operations that need to be performed in it
const formName = [form1, form2, form3, form4]

//创建一个验证方法
const validates = (item) => {
    
    
  return new Promise((resolve, reject) => {
    
    
    if (!this.$refs[item]) {
    
    
      resolve()
      return false
    }
    this.$refs[item].validate((valid) => {
    
    
      if (valid) {
    
    
        resolve()
      } else {
    
    
        reject()
      }
    })
  })
}

//将验证方法放入promise.all
Promise.all(formName.map((item) => validates(item)))
.then((=>{
    
    
  console.log('验证成功');
}))
.catch((=>{
    
    
  console.log('验证失败');
}))
  • Form verification reset is the same operation, just validateschange the method to the reset method resetFields.

Guess you like

Origin blog.csdn.net/yuan0209/article/details/128055409