data() {
return {
_beforeUnload_time:0,
_gap_time:0,
}
},
mounted() {
//1.监听关闭浏览器本窗口
window.addEventListener('beforeunload', e => this.beforeunloadHandler(e))
window.addEventListener('unload', e => this.unloadHandler(e))
//2.一小时注销用户
let _this = this; // 声明一个变量指向Vue实例this,保证作用域一致
this.timer = setInterval(() => {
_this.$store.commit('clearToken');
_this.$router.push("/login");
}, 1000*60*60)
},
destroyed() {
window.removeEventListener('beforeunload', e => this.beforeunloadHandler(e))
window.removeEventListener('unload', e => this.unloadHandler(e))
if (this.timer) {
clearInterval(this.timer); // 在Vue实例销毁前,清除我们的定时器
}
},
methods: {
beforeunloadHandler(e){
this._beforeUnload_time = new Date().getTime();
},
unloadHandler(e){
let _gap_time = new Date().getTime() - this._beforeUnload_time;
if (_gap_time <= 5) {
this.$store.commit('clearToken');
this.$router.push("/login");
}
},
}
参考 https://www.cnblogs.com/aixuexi-504682107/p/13605943.html
当关闭页面时,清除localStorage
var _beforeUnload_time = 0,
_gap_time = 0;
window.onunload = function () {
_gap_time = new Date().getTime() - _beforeUnload_time;
if (_gap_time <= 5) {
var storage = window.localStorage;
storage.clear();
}
};
window.onbeforeunload = function () {
_beforeUnload_time = new Date().getTime();
};