在beforeDestroy中销毁localStorage中的值无效
目的:在关闭窗口时删除localStorage中的数据方法1:beforeDestroy中删除想要在组件销毁的时候删除localStorage中的变量,结果发现无效beforeDestroy在页面刷新的时候不会执行,但是在页面跳转的时候会执行(this.router.push,this.router.push,this.router.push,this.router.replace),但是关闭窗口
·
beforeDestroy中销毁localStorage中的数据无效
目的:在关闭窗口时删除localStorage中的数据
方法1:beforeDestroy中删除
beforeDestroy() {
localStorage.removeItem("info");
}
想要在组件销毁的时候删除localStorage中的变量,结果发现无效
beforeDestroy在页面刷新的时候不会执行,但是在页面跳转的时候会执行(this.router.push,this.router.push,this.router.push,this.router.replace),但是关闭窗口的时候不会执行
该强制关闭窗口的时候,浏览器都会在js执行的间隙立马中止所有后续js执行(vue的beforeDestroy也不例外),并关闭该窗口。
方法2:unload事件中删除
mounted() {
window.addEventListener("unload", () => {
localStorage.removeItem("hello");
});
},
可以达到删除的效果,但是有一个问题,就是页面刷新的时候也会执行,这个不是想要的结果
最后还是改为放到sessionStorage中了,还是回到了最初的想法
onload onunload beforeunload的执行时机
页面加载时只执行onload
页面关闭时先执行onbeforeunload,最后onunload
页面刷新时先执行onbeforeunload,然后onunload,最后onload
更多推荐
所有评论(0)