首页 > 解决方案 > Vue async / await 与 $emit

问题描述

我有一个对话框组件,它在提交时执行两个异步函数。我的目标是保持对话框打开并显示加载状态,直到两个功能都完成。之后,我想关闭对话框。

我在父组件中定义的提交函数如下所示:

 async submit() {
    await this.foo1();
    await this.foo2();
}

此函数作为道具传递给对话框组件:

<app-dialog @submit="submit" />

在我的对话框组件中,单击按钮,我尝试这样做:

async onClick() {
    await this.$emit('submit');
    this.closeDialog();
},

但是,对话框会立即关闭,而不是等待执行提交。实现这一目标的最佳方法是什么?

标签: javascriptvue.jsasync-await

解决方案


我设法通过在对话框组件中传递回调来找到解决方案:

submit() {
    this.$emit('submit', () => this.closeDialog())
},

然后在我的父组件中调用该回调:

async submit(closeDialog) {
    await this.foo1();
    await this.foo2();
    closeDialog()
}

但一定有比这更好的解决方案!


推荐阅读