需求场景一:用户退出时清空localStorage并告知后台用户退出,保持登录状态时关闭窗口或者浏览器达到相同目的
实现:
// 在mounted中触发beforeunload事件以及在destroyed中触发beforeunload事件
// 当文档或一个子资源正在被卸载时, 触发 unload事件,unload在beforeunload之后被触发
// 参考地址:https://blog.csdn.net/weixin_45372546/article/details/108538026
// 要做到全局监听,我直接放在了入口文件中 因个人项目而异
data(){
return {
_beforeUnload_time:'',
_gap_time:''
}
},
mounted() {
window.addEventListener("beforeunload", (e) => this.beforeunloadHandler(e));
window.addEventListener("unload", (e) => this.unloadHandler(e));
},
methods: {
beforeunloadHandler(e) {
this._beforeUnload_time = new Date().getTime();
//e.returnValue = '关闭提示'; 弹窗
},
unloadHandler(e) {
let _this = this;
this._gap_time = new Date().getTime() - this._beforeUnload_time;
//判断是窗口关闭还是刷新
if (this._gap_time <&#