简体   繁体   中英

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;
},

You can remove the event listener on beforeDestroy hooks

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM