Beusebiu
Beusebiu

Reputation: 1513

removeEventListener when change route Vuejs

When I mount the page I add an eventListner and if the user want to change the route I want to remove it. But in my case after I change the route that event is still available and if I close the tab I still get an alert.

  mounted: function () {
    window.addEventListener("beforeunload", this.detectTabClose);
  },

  beforeRouteLeave(to, from, next) {
    //gets here and the route is changed, but this event is not removed
    window.removeEventListener("beforeunload", this.detectTabClose, true);
    next();
  },

detectTabClose(e) {
    var confirmationMessage = "o/";
    (e || window.event).returnValue = confirmationMessage;
    return confirmationMessage;
},

Upvotes: 3

Views: 1332

Answers (1)

lissettdm
lissettdm

Reputation: 13080

You can remove the event listener on beforeDestroy hooks

beforeDestroy() {
   window.removeEventListener("beforeunload", this.detectTabClose);
},

Upvotes: 3

Related Questions