函数取弹窗值同步执行处理方案
在实际开发中有这样一种情况:
在页面中有一个按钮提交信息,点击提交时需要弹出一个弹窗,拿到弹窗信息值再向下执行,在掉弹窗点确定时我不想再掉一个接口去传值,我想在点击提交时连弹窗中的值一块传给后端。
下面是我的解决思路:
提交按钮需要拿到弹窗内填写的值,再向下执行调用接口
async testFun() {
// 1.调用打开弹窗方法,并使用await使得代码同步执行
// 2.await结合promise可以拿到promise返回值
let needs = await this.open()
this.$http({
url: Url,
method: 'POST',
data: needs,
loading: true
}).then(res => {
...
})
}
- 打开弹窗return一个promise的回调函数
data() {
return {
visibleDialog: false,
callBackInfo: null
}
}
// 打开弹窗方法 ---- 就是变量打开的elementui弹窗
open() {
return new Promise(cb => {
this.callBackInfo = cb // 变量接受promise的回调函数
this.visibleDialog = true
})
}
- 弹窗点确定按钮的时候传值
confirmDialog() {
this.visibleDialog = false
// needs为弹窗所拿到的值,通过callBackInfo回传最终函数内
this.callBackInfo(this.needs)
}
这样就实现了同一个函数中,触发弹窗点击确定后,函数中代码同步执行。
- 代码实现核心异步方案:await + promise