Vue:未删除 beforeunload 事件侦听器

Vue: beforeunload event listener is not being removed

我正在研究撤消删除功能,它包含一个小模式,允许用户在有限的时间内undo/delay 操作(类似于 gmail)。但是,我想确保在用户决定导航到另一个 window 或关闭选项卡时执行该操作,我这样做是这样的:

mounted() {
  this.timeout = setTimeout(() => {
    this.close(true);
  }, this.duration);
  window.addEventListener('beforeunload', this.forceDestroyHandler, { capture: true });
},
methods: {
  close(deleteBeforeClosing) {
    if (deleteBeforeClosing) {
      clearTimeout(this.timeout);
      // This is the function dispatching to the store and deleting the item
      this.destructiveEvent(this.category, this.item.id);
    }
    this.$emit('close');
}

然后我(尝试)删除 beforeDestroy 上的事件侦听器:

beforeDestroy() {
  this.forceDestroy();
  window.removeEventListener('beforeunload', this.forceDestroyHandler, {capture: true});
},

但是,似乎永远不会调用 beforeDestroy,这意味着永远不会删除事件侦听器 - 因此,如果用户决定关闭选项卡或导航,则会提示一条消息,即使撤消组件甚至不再显示.如果用户单击取消,则会向商店发送另一个操作,尝试删除已删除的项目,从而导致服务器错误。

我也尝试将 removeEventListener 放在其他地方,但我一直遇到同样的问题。

进一步阐述我的评论:您的 onbeforeunload 事件侦听器未绑定的原因是因为 beforeDestroy() 生命周期挂钩仅在销毁 VueJS 组件时触发。当您关闭浏览器时 tab/window,整个线程都会被擦除,这不会触发组件销毁。

由于您只想在模式关闭后删除侦听器,因此在 close() 方法中执行此操作很有意义:因此您的方法有效。