[vue] Switch the window, determine whether the token has changed, and refresh the page if it changes.

Operate in the App.vue page

<template>
  <div id="app">
    <router-view></router-view>
  </div>
</template>

<script>
import { getoldToken, setoldToken, getToken } from "@/utils/auth";

export default {
  name: "App",
  mounted() {
    /*浏览器标签页切换会触发"visibilitychange"事件*/
    document.addEventListener("visibilitychange", this.handleVisiable);
  },
  destroyed() {
    document.removeEventListener("visibilitychange", this.handleVisiable);
  },
  methods: {
    handleVisiable(e) {
      /*处理逻辑*/
      //1、如果要发送请求,那么最好用navigator.sendBeancon(url),它可以保证在浏览器页面销毁前,将请求发送出去。如果使用XMLHttprequest或者基于它实现的axios发送请求,那么可能出现浏览器关闭了,但是请求没有发送出去的情况。
      //2、如果单纯监听切换浏览器标签页、单纯监听刷新页面,那么可以使用axios发送请求
      //3、navigator.sendBeancon(url)默认发送POST请求
      //4、举例如下:
      // const URL = process.env.VUE_APP_BASE_API + "/uploads/deleteAll";
      // navigator.sendBeacon(URL);
      switch (e.target.visibilityState) {
        case "prerender":
          // console.log("网页预渲染,内容不可见");
          break;
        case "hidden":
          // console.log("内容不可见,处理后台、最小化、锁屏状态");
          // alert("警告!你已经离开当前答题页面");
          setoldToken(getToken("vue_DEJIAN__token"));
          break;
        case "visible":
          // console.log("处于正常打开");
          if (
            getToken("vue_DEJIAN__token") !==
            getoldToken("vue_DEJIAN__Old_token")
          ) {
            location.reload();
          } 
          break;
      }
    },
  },
};
</script>

<style lang="scss"></style>

Guess you like

Origin blog.csdn.net/Qxn530/article/details/132016528