关于vue中监听页面刷新事件(f5)

js的beforeunload事件,每个页面只能触发一次吗?我想实现在某个特定页面f5刷新都弹出这个提示框,然后其他页面不受影响。可是我设置后这个页面只能触发一次,并且如果跳转到非当前页面也会触发一次,但只触发一次。不知道哪里设置的不正确
image.png

 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))
    });
阅读 5.9k
1 个回答

改成如下就行:

onMounted(() => {
  window.addEventListener('beforeunload', handleBeforeunload)
});
onUnmounted(() => {
  window.removeEventListener('beforeunload',handleBeforeunload )
});

因为你使用的匿名函数会导致在unmounted没有移除handleBeforeunload方法,
所以跳到其他页面刷新会再触发一次

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题