js的beforeunload事件,每个页面只能触发一次吗
?我想实现在某个特定页面f5刷新都弹出这个提示框,然后其他页面不受影响。可是我设置后这个页面只能触发一次,并且如果跳转到非当前页面也会触发一次,但只触发一次。不知道哪里设置的不正确
const handleBeforeunload = (e:Event,num:number)=>{
if (e) {
e.returnValue = '关闭提示'
}
return true
}
onMounted(() => {
window.addEventListener('beforeunload', e => handleBeforeunload(e))
});
onUnmounted(() => {
window.removeEventListener('beforeunload', e => handleBeforeunload(e))
});
改成如下就行:
因为你使用的匿名函数会导致在unmounted没有移除handleBeforeunload方法,
所以跳到其他页面刷新会再触发一次