Vue implements the function of closing the browser and logging out (differentiate between closing and refreshing)

Vue implements the function of closing the browser and logging out (differentiate between closing and refreshing)

Project background: It is necessary to clear the cache, visit again, and log in again after closing the browser.

Solution:

data() {
    
    
    return {
    
    
      gap_time: 0,
      beforeUnload_time: 0,
    };
  },
  methods: {
    
    
    // 关闭窗口之前执行
    beforeunloadHandler() {
    
    
      this.beforeUnload_time = new Date().getTime();
    },
    unloadHandler() {
    
    
      this.gap_time = new Date().getTime() - this.beforeUnload_time;
      //判断是窗口关闭还是刷新 毫秒数判断 网上大部分写的是5
      if (this.gap_time <= 10) {
    
    
        localStorage.clear();
        //logOut() // 退出登录接口 这里应当换为个人的登出方法
      } else {
    
    
        
      }
    },
  },
  destroyed() {
    
    
    // 移除监听
    window.removeEventListener("beforeunload", () => this.beforeunloadHandler());
    window.removeEventListener("unload", () => this.unloadHandler());
  },
  mounted() {
    
    
    // 监听浏览器关闭
    window.addEventListener("beforeunload", () => this.beforeunloadHandler());
    window.addEventListener("unload", () => this.unloadHandler());
  }

sessionStorage,localStorageDescription:
(1) sessionStorage(Temporary storage): Maintain a storage area for each piece of data. It will be created when the browser is opened and disappear when the browser is closed.
(2) localStorage(Long-term storage): Same as the former, the difference is that the data still exists after the browser is closed

Guess you like

Origin blog.csdn.net/weixin_44021888/article/details/130725989