vue 监听网页关闭/浏览器关闭事件


1.methods中定义窗口关闭/浏览器关闭之后处理内容,例如删除cookie、session、local storage 等

methods: {
    beforeunloadHandler(e) {
      console.log('关闭窗口之后')
    }
}

2.mounted 绑定窗口关闭监听事件

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

3.destroyed 解绑事件

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

以上方法刷新页面也会触发

区分关闭或者刷新:

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,是否异步
                })
      }
    }
  },
}       

 


php 机型 浏览器 操作系统判断

vue 数据赋值给新变量后,原数据也随新变量对数据的变化而变化

评 论
更换验证码