問題描述:
一個(gè)新增頁面里有多個(gè)組件,在新增頁面對(duì)組件進(jìn)行 校驗(yàn) 必填項(xiàng)等,發(fā)現(xiàn)效驗(yàn)有異步問題;
之前寫法
// 提交效驗(yàn)
handleSubmit() {
this.subForm = JSON.parse(JSON.stringify(this.baseInfo))
let _this = this
let pass = true
// 表單驗(yàn)證
// 基本信息
this.$refs.form1.$refs.baseInfo.validate((valid) => {
if (!valid) {
pass = false
}
})
if(pass) {
// 調(diào)接口
}
}
異步原因:表單中有級(jí)聯(lián),下拉框等,是需要調(diào)接口的,需要時(shí)間,就會(huì)異步;
解決問題方法:使用 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) {
// 接口請(qǐng)求
_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)
})