Vue $emit in Promise Vue $emit in Promise vue.js vue.js

Vue $emit in Promise


In my case, the child component was removed from the parent using "v-if" directive when an API request was initialized.

Then, when my request finished, the child component emitted an event correctly, but in this moment the child wasn't rendered in the parent component's DOM, so the parent couldn't listen to that event.


I think it was because of the 'this' binding.

You need to bind the this of Vue component instance into the callback function.

const callbackFn = function(res) {  if (res) {    Helpers.callToast(this, 'is-success', this.$root.$t('profile.avatar_upload'))    this.$emit('success')  }}.bind(this);UsersAPI.updateAvatar(this.user.id, data, fileExt).then(callbackFn)

or you could simply create a new variable to save your Vue instance, then refer your callback function to use it.

const self = this;UsersAPI.updateAvatar(this.user.id, data, fileExt).then(res => {  if (res) {    Helpers.callToast(this, 'is-success', self.$root.$t('profile.avatar_upload'))    self.$emit('success')  }})