I'm building the logic for an 'undo delete' - action. For that, I'm using an Event Bus to send an event to two unrelated components like so:
Undo.vue:
EventBus.$emit(`confirm-delete-${this.category}`, this.item.id);
The name of the event(this.category
) is based on props coming from a parent (ConfirmDeleteModal.vue
) and then received as follows:
CategoryA.vue
created() {
EventBus.$on('confirm-delete-category-a', (id) => {
this.confirmDelete(id);
});
},
CategoryB.vue
created() {
EventBus.$on('confirm-delete-category-b', (id) => {
this.confirmDelete(id);
});
},
My issue: For some reason, the event for category-a
is emitted and received twice (category-b
works fine). I have to listen to the confirm-event
constantly, therefore I can't remove the event listener after I received the event or listen only $once
. Any ideas how to solve this (maybe with Vuex)? Thanks!
I was also facing the same kind of issue and then after some research, I got this solution.
You have defined your component CategoryA.vue
two times in your application which is causing the function to run twice which is in this case CategoryA.vue
Solution:
You have to call destroyed()
after the created()
Like:
created() {
EventBus.$on('confirm-delete-category-a', (id) => {
this.confirmDelete(id);
}),
},
destroyed() {
EventBus.$off('confirm-delete-category-a');
},