Search code examples
javascriptvue.jsvue-router

Why does it make api calls from other routes if I'm not already in it, Vue Router


I am creating a Vue application where in each route I make a table that makes a call to an API. This table is in a separate component, where it listens for an event from an eventBus in order to reload the data.

DataTable.vue

this.$bus.$on('reloadData', () => {
  this.getRecords()
})

Route A

<datatable></datatable>

Route B

<datatable></datatable>

Component inner Router B

 this.$bus.$emit('reloadData')

As you can see, the event is emitted from a modal component of a route B (I'm here), but when doing this, if before going to route B, I was in a route A,C,D when I emit the event from the modal requests are made the same number of times as the routes that visit(A,C,D) and that have the datatable component. as if they will stack and the component of routes A,C,D are active but it is not so since I am in route B


Solution

  • this.$bus.$on(...) creates a new event listener for every route you visit. since $bus is a global object, these event listeners don't get removed just because you navigate away from a route. You need to make sure before you navigate away that you remove the old listener in the destroyed lifecycle hook of the component.

    destroyed() {
        this.$bus.$off('reloadData');
    }