温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-07-26 07:09:28 来源:网络 阅读:802 作者:wx5a684dffd5e61 栏目:web开发

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

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI