监听关闭页面事件 ajax,Vue中监听窗口关闭事件并在窗口关闭前发送请求

Vue中监听窗口关闭事件并在窗口关闭前发送请求

发布时间:2020-07-26 07:09:28

来源:51CTO

阅读:165

作者:wx5a684dffd5e61

Vue中监听窗口关闭事件并在窗口关闭前发送请求,代码如下:

mounted() {

window.addEventListener('beforeunload', e => this.beforeunloadHandler(e))

window.addEventListener('unload', e => this.unloadHandler(e))

},

destroyed() {

window.removeEventListener('beforeunload', e => this.beforeunloadHandler(e))

window.removeEventListener('unload', e => this.unloadHandler(e))

},

methods: {

beforeunloadHandler(){

this._beforeUnload_time=new Date().getTime();

},

unloadHandler(e){

this._gap_time=new Date().getTime()-this._beforeUnload_time;

debugger

//判断是窗口关闭还是刷新

if(this._gap_time<=5){

//如果是登录状态,关闭窗口前,移除用户

if(!this.showLoginButton){

$.ajax({

url: '/pictureweb/user/remove',

type: 'get',

async:false, //或false,是否异步

})

}

}

},

}

window.beforeunload事件在window.unload事件之前执行。同时注意ajax请求方式必须为同步请求,所以不能使用axios,因为axios不能执行同步请求。

分享一些技术学习视频资料:https://pan.baidu.com/s/13dbR69NLIEyP1tQyRTl4xw

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值