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();
      },
      formatDate() {
        let date = new Date();
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let day = date.getDate();
        let hour = date.getHours();
        let minute = date.getMinutes();
        let second = date.getSeconds();
        return (
          year +
          "-" +
          this.formatTen(month) +
          "-" +
          this.formatTen(day) +
          " " +
          this.formatTen(hour) +
          ":" +
          this.formatTen(minute) +
          ":" +
          this.formatTen(second)
        );
      },
      formatTen(num) {
        return num > 9 ? num + "" : "0" + num;
      },
      unloadHandler() {
        let time = this.formatDate();
        console.log(time)
        this._gap_time = new Date().getTime() - this.beforeUnload_time;
        console.log(this._gap_time)
        //判断是窗口关闭还是刷新
        if (this._gap_time <= 5) {
          console.log('执行关闭方法')
          debugger
        }
      }
    },

版权声明:本文为weixin_44880056原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。