想要在页面关闭时请求后台,来更新在线人数
网上找了,很多方法,不是刷新不能判断,就是后台请求不成功,还有浏览器不兼容
后面综合多种方法找到了解决方案,代码如下:
data() {
return {
//时间用作判断刷新或关闭判断
_beforeUnload_time:0,
_gap_time:0,
}
}
mounted() {
//添加事件 当页面卸载(关闭)或刷新时调用
window.addEventListener('beforeunload', e => this.beforeunloadHandler(e))
// window.addEventListener('unload', e => this.unloadHandler(e))
//添加事件 当用户离开页面时调用
window.addEventListener( 'unload', e => this.set() );
},
//当用户离开此界面时执行(销毁事件)
destroyed() {
//删除 当页面卸载(关闭)或刷新时调用事件
window.removeEventListener('beforeunload', e => this.beforeunloadHandler(e))
//删除 当用户离开页面时调用事件
window.removeEventListener('unload', e => this.set() )
},
methods: {
//浏览器关闭执行函数
set(){
console.log('我是要调用的函数')
this._gap_time=new Date().getTime()-this._beforeUnload_time;
if(this._gap_time<=5){
//后台访问地址
let url = 'xxxxxxxx'
// this.headers 请求头
axios.get(url, { headers: this.headers }).then(response => {
debugger
//成功了
}).catch(error => {
this.$message.error(error)
})
}
},
beforeunloadHandler(){
this._beforeUnload_time=new Date().getTime();
},
}
恩,问题解决了记录下来以作保存