我有一个对话框组件,它在submit上执行两个异步函数。我的目标是保持对话框打开并显示一个加载状态,直到两个函数都完成为止。之后,我想关闭对话框。
在父组件中定义的提交函数如下所示:
async submit() {
await this.foo1();
await this.foo2();
}
此函数作为支柱传递给对话框组件:
<app-dialog @submit="submit" />
在对话框组件中,在单击按钮时,我尝试这样做:
async onClick() {
await this.$emit('submit');
this.closeDialog();
},
但是,对话框将立即关闭,而不是等待提交执行。做这件事最好的方法是什么?
发布于 2021-03-11 13:51:22
通过在对话框组件中传递回调,我设法找到了一个解决方案:
submit() {
this.$emit('submit', () => this.closeDialog())
},
然后在我的父组件中调用这个回调:
async submit(closeDialog) {
await this.foo1();
await this.foo2();
closeDialog()
}
但一定有比这更好的解决办法!
发布于 2021-03-11 15:24:14
对于这类问题,有一种替代模式,即将回调函数作为支柱传递。
在对话框组件上:
props: {
onSubmit: {
type: Function,
required: true // this is up to you
},
[...]
// in your methods
async onClick() {
if (this.onSubmit && typeof this.onSubmit === 'function') {
await this.onSubmit();
}
this.closeDialog();
}
然后,在父组件中:
<app-dialog :on-submit="submit" />
[...]
// in your methods:
async submit() {
await this.foo1();
await this.foo2()
}
不过,请记住一些事情
,
https://stackoverflow.com/questions/66583752
复制相似问题