Neha Soni
Neha Soni

Reputation: 4704

How can I remove manually added event listeners on beforeDestory hook of one component before redirecting to any another component, in Vuejs2?

I want to know the concept of the below thing-

I have created one component and set up its respected event listeners. Now, I want to remove those listeners on this component's beforeDestroy hook before redirecting to another route that will create another component. but what I noticed is, beforeDestory hook of the first component is calling even after the second component's created hook.

I want to destroy the first component completely and then create another component.

// To set up the event listeners
created() {
  this.EventBus.$on('myCustomEvent', payload => {
    // some code here
  )}
}

// To destroy the event listeners
beforeDestroy() {
  this.EventBus.$off('myCustomEvent');
}

Any suggestions?

Upvotes: 0

Views: 227

Answers (1)

grovskiy
grovskiy

Reputation: 788

In search of an answer to your question, I came to the conclusion that it is better to refuse to use EventBus altogether.

Here is some information on this and some thoughts from there:

I have that feeling that having an EventBus in Vue is an anti-pattern, especially if you’re using VueX but I can’t quite put my finger on it. At the point you want to be sharing data like that, wouldn’t it be better to use a store to handle all of those “events” / “mutations”?

Also, looking at the solution to this issue, you are doing everything right and there is no other way.

Upvotes: 1

Related Questions