I am handling an upload for images - based on a Promise. In the "then" - callback I want to $emit an event. I call it 'success'. My VueDevTools shows me an success event, but in the parent component the "linked" method is never called. Is it possible that this.$emit('success') does not work within Promises?
Example Code - Child component:
UsersAPI.updateAvatar(this.user.id, data, fileExt).then(res => {
if (res) {
Helpers.callToast(this, 'is-success', this.$root.$t('profile.avatar_upload'))
this.$emit('success')
}
})
Example Code - Parent Component
<Avatar @success="test" :user="user" />
The method "test" in parent component is NEVER called, but the event is called in the vue dev tools. If I emit the event before the Promise, I get the result I wish.
Can you may help me? Kind regards
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')
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With