vue项目PC端超时未操作退出登录

126 阅读1分钟
<template>
  <div id="app">
    <router-view />
  </div>
</template>

<script>
import { mapActions } from "vuex";
export default {
  name: "App",
  data() {
    return {
      lTime: new Date().getTime(), // 最后一次点击的时间
      cTime: new Date().getTime(), //当前时间
      tOut: 60 * 10 * 1000, //超时时间10min  关闭超时检测时,注释此行代码
      timer: null,
    };
  },
  methods: {
    tTime() {
      this.cTime = new Date().getTime();
      if (this.tOut && this.cTime - this.lTime > this.tOut) {
        //未登录状态
        if (localStorage.getItem("token")) {
          this.handleLogOut().then(() => {
            this.$router.push({
              name: "login",
            });
          });
          this.$Message.error({
            content: "登录超时,请重新登录",
            duration: 3,
          });
        } else {
          this.lTime = new Date().getTime();
        }
      }
    },
    // 退出登录点击事件
    ...mapActions(["handleLogOut"]),
  },
  created() {
    window.addEventListener(
      "click",
      () => {
        this.lTime = new Date().getTime();
      },
      true
    );
  },
  mounted() {
    if (this.timer) {
      clearInterval(this.timer);
    }
    this.timer = setInterval(this.tTime, 1000);
  },
  beforeDestroy() {
    clearInterval(this.timer);
    window.removeEventListener("click", () => {}, true);
  },
};
</script>