Vue:beforeunload事件侦听器未被删除



我正在开发一个撤消删除功能,它由一个小模式组成,允许用户在有限的时间内撤消/延迟操作(类似于gmail(。然而,如果用户决定导航到另一个窗口或关闭选项卡,我想确保执行该操作,我这样做:

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事件侦听器没有解除绑定的原因是,只有当VueJS组件被破坏时,beforeDestroy()生命周期挂钩才会被触发。当您关闭浏览器选项卡/窗口时,整个线程都会被擦除,这不会触发组件销毁。

由于您只想在模态关闭后删除侦听器,因此在close()方法中删除侦听器是有意义的:因此您的方法有效。

最新更新