Vue 异步/等待 $emit

时间:2021-03-11 13:42:09

标签: javascript vue.js async-await

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

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

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

这个函数作为 prop 传递给对话框组件:

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

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

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

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

2 个答案:

答案 0 :(得分:1)

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

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

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

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

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

答案 1 :(得分:0)

这种问题有另一种模式,即将回调函数作为 prop 传递。

在你的对话框组件上:

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()
}

请记住一些事情

  1. 处理承诺的方式很重要。例如,如果您想在出现错误时保持模态打开,您可以在模态组件中进行错误处理,或者至少将一些错误转发给它。

  2. 进一步探索函数的验证是值得的,例如检查它是否真的返回了一个承诺,然后等待它,否则做其他事情。

  3. 即使只是一点点,这种模式也会给你的解决方案增加一点耦合,所以你不想用回调函数替换所有事件!