Beusebiu
Beusebiu

Reputation: 1523

Method is called on other routers, Vuejs

I have a method (that detects when the tab is closed) that is called on created, on a component, but if I access another component , that method is still active.

created() {
  this.detectTabClose();
},

methods: {
    detectTabClose() {
      const onWindowTabClose = e => {
        var confirmationMessage = "o/";
        (e || window.event).returnValue = confirmationMessage; 
        this.submitBeforeCloseTab();
        return confirmationMessage;
      };
      window.addEventListener("beforeunload", onWindowTabClose);
    },
}

Upvotes: 0

Views: 54

Answers (2)

Michael
Michael

Reputation: 2631

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.

Upvotes: 2

Alex Brohshtut
Alex Brohshtut

Reputation: 2060

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.

Upvotes: 1

Related Questions