VUE监听网页关闭和隐藏显示

一、监听网页关闭并执行退出操作

1.mounted()中创建页面关闭的监听

window.addEventListener("beforeunload", (e) => this.beforeunloadHandler(e));
window.addEventListener("unload", (e) => this.unloadHandler(e));

 2.监听的是页面关闭之前,对应的方法可以写做

// 页面关闭之前,触发提示框
    beforeunloadHandler(e) {
      if (e) {
        e = e || window.event;
        console.log(e);
        if (e) {
          e.returnValue = "关闭提示";
        }
        return "关闭提示";
      }
    },

3.监听的是页面关闭的时候,这里面可以调用自己的异步处理

  async myfuncation(e) {
      // 
      await &&**********
  },

4.destroyed()中,注销监听

destroyed() {
    window.removeEventListener("beforeunload", (e) =>
      this.beforeunloadHandler(e)
    );
    window.removeEventListener("unload", (e) => this.unloadHandler(e));
  },

 二、VUE监听网页隐藏显示

mounted(){
    //添加监听事件
    window.addEventListener('beforeunload', e => this.beforeunloadHandler(e));

    document.addEventListener('visibilitychange',function(e){
      console.log(document.visibilityState);
      let state = document.visibilityState
      if(state == 'hidden'){
        console.log(document.visibilityState,'用户离开了');
      }
      if(state == 'visible'){
        console.log(document.visibilityState,'回来了');
      }
    });

  }

猜你喜欢

转载自blog.csdn.net/qq_42717015/article/details/129944355