el-form 表单校验 异步问题 解决

问题描述:
一个新增页面里有多个组件,在新增页面对组件进行 校验 必填项等,发现效验有异步问题;
之前写法

// 提交效验
 handleSubmit() {
        this.subForm = JSON.parse(JSON.stringify(this.baseInfo))
            let _this = this
            let pass = true
            // 表单验证
            // 基本信息
               this.$refs.form1.$refs.baseInfo.validate((valid) => {
                    if (!valid) {
                        pass = false
                    }
                })
             if(pass) {
                // 调接口
              }
         }

异步原因:表单中有级联,下拉框等,是需要调接口的,需要时间,就会异步;
解决问题方法:使用 Promise

 let form1 = new Promise((resolve, reject) => {
      this.$refs.form1.$refs.baseInfo.validate((valid) => {
            if (!valid) {
                    pass = false
             }
         })
       resolve();
  })

Promise.all([form1,form2,form3,form4]).then(res => {
    if(pass) {
         // 接口请求
            _this.subForm.belongGridName = _this.baseInfo.belongGrid.join("->")
            _this.subForm.addressNow = _this.baseInfo.address.join("->") + "->" + _this.subForm.addressDetail
          this.loading = true
          this.$axios.post(////", this.subForm)
          .then((res) => {
              this.$message.success("新增成功")
              this.$router.back()
           })
            .catch(err=>{
              this.loading = false
              this.$message.error(err.message)
         })
   }
}).catch(err => {
     Console.log(err)
})

你可能感兴趣的:(el-form 表单校验 异步问题 解决)