更改路由 Vuejs 时的 removeEventListener

removeEventListener when change route Vuejs

当我挂载页面时,我添加了一个 eventListner,如果用户想要更改路由,我想将其删除。 但在我的情况下,在我更改路线后,该事件仍然可用,如果我关闭选项卡,我仍然会收到警报。

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

您可以删除 beforeDestroy 挂钩上的事件侦听器

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