Shadam
Shadam

Reputation: 1122

VueJs $emit in component not triggered parent when fired in async method

I have an async method in my component, I want to await for the axios request and then emit an event to the parent.

When in the async/await pattern, the event is emitted but not catch by parent

async save() {
  if (this.canSave) {
    await this.savePlot()      
    this.$emit('plot-saved');
  }
}

if I set it as a normal function no problem, the parent catch the event :

save() {
  if (this.canSave) {
    this.savePlot()      
    this.$emit('plot-saved');
  }
}

my component in the parent vue file :

<PlotForm @plot-saved="close(true)" />

Upvotes: 1

Views: 770

Answers (1)

Adagio
Adagio

Reputation: 21

I found this thread, when I ended up with the same problem as you had, unfortunately there was no answers here

Never figured out why it was not working. In my code I added console.log after calling with await, but before $emit. The console.log was correctly called, so the problem lies with the $emit functionality

I did manage to find a solution that is useful. Add this nice tool to your project https://github.com/developit/mitt

In my project I added a variable called emitter in an external normal .js file and added this to the vue code:

mounted()
{
        window.emitter = window.mitt();

        window.emitter.on('group-text-closed', this.GroupTextClosed)
},

And then in the function that needs to emit, add this instead

CloseGroupText()
{
        await SomeApiCallFunctionWorthWaitingFor();

        window.emitter.emit('group-text-closed');
},

This also has the added benefit that you can call it in some child deep down and still easily catch it in the root parent

I hope this can help out anybody else who is in the same situation

Upvotes: 1

Related Questions