Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js method called multiple times using $emit and $on when it should only be called once

I'm using a bus to allow components to interact with other components via the method described in this link: https://forum.vuejs.org/t/create-event-bus-in-webpack-template/4546/2 .

I have a method that is called in created hook which uses the bus to emit an event.

created () {
  this.getReviewDeck()
},
myMethod () {
    bus.$emit('increment')
}

In another component (which is contained in the above component) I attach the event listener in the created hook as below:

created () {
  bus.$on('increment', this.incrementCount)
},
incrementCount () {
  console.log('count incremented')
}

If I visit the component the first time everything works properly and the console will log 'count incremented' one time. However, if I leave the component and then navigate back to it the next time 'count incremented' will be logged twice, and if I leave and come back again it will now be logged three times etc.

I can't quite figure out what exactly is going on or how best to solve this issue so that every time I go to the component the message is only logged once instead of multiple times.

like image 426
dpst Avatar asked Sep 05 '25 12:09

dpst


2 Answers

Had to remove the event handler on destroy.

 beforeDestroy () {
    EventBus.$off('increment', this.incrementCount)
 },
like image 162
dpst Avatar answered Sep 08 '25 10:09

dpst


You can use $.once

created () {
  bus.$once('increment', this.incrementCount)
},
like image 20
Jdmiguel Avatar answered Sep 08 '25 10:09

Jdmiguel