<template>
<div id="app"></div>
</template>
<script>
export default {
name: "App",
data() {
return {
beforeunloadTime: 0,
unloadTime: 0
};
},
mounted() {
window.addEventListener('beforeunload', e => this.beforeunloadHandler(e));
window.addEventListener('unload', e => this.unload(e));
},
destroyed() {
window.removeEventListener('beforeunload', e => this.beforeunloadHandler(e));
window.removeEventListener('unload', e => this.unload(e));
},
methods: {
beforeunloadHandler() {
this.beforeunloadTime = new Date().getTime()
},
unload() {
this.unloadTime = new Date().getTime()
// window.localStorage.setItem('timer', String(this.unloadTime - this.beforeunloadTime))
// 本地通过localStorage中的数据看出,关闭事件间隔小于1,刷新则大于8
if (this.unloadTime - this.beforeunloadTime <= 1) {
// 执行退出登录
this.logout(true)
}
}
}
};
</script>
离开当前路由时,提示是否要离开当前页面
beforeRouteLeave(to, form, next) {
this.$confirm('正在处理消息,请确认是否离开?', { // element-ui 确认对话框为例
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning',
})
.then(async () => {
this.beforeunloadHandler() // 业务需要,可在此写入
next() // 点击确定,确认离开
})
.catch(() => {
location.reload() // 刷新页面 业务需要
next(false) // 点击取消,不离开当前页面
})
return
},