[Vuejs]-Method is called on other routers, Vuejs

2πŸ‘

βœ…

This happens because you are setting up a event-listener on the windows object. So even though the tab is gone the listener is still there.

To fix this you need to "clean up" before the tab component is destroyed.

Just like created there is a life-cycle hook for this beforeDestroy. In this hook you can use removeEventListener that takes the same function as input. To achieve this you move the function to methods (or elsewhere) where so that it can be referenced in both places.

created() {
  window.addEventListener('beforeunload', this.onWindowTabClose)
},
beforeDestroy() {
  window.removeEventListener('beforeunload', this.onWindowTabClose)
},
methods: {
  onWindowsTabClose(e) {
    ...
  }
}

An alternative method that uses a Vue event-listener with the $once method. $once works like $on but stops listening when the it encounters the first event that it listens to.

created() {
  const onWindowsTabClose = (e) => {
    ...
  }
  window.addEventListener('beforeunload', onWindowTabClose)
  this.$once('hook:beforeDestroy', function () {
    window.removeEventListener('beforeunload', onWindowTabClose)
  })
},

The advantage of this approach is that your code is one place. This makes your components easier to reason about once they start to grow.

πŸ‘€Michael

1πŸ‘

Of course it will be active – you bind it on window, which is global across all, well, window.

In order to prevent this behaviour, you need to removeEventListener when component is destroyed.

Leave a comment