监听检测页面长时间未操作后事件

代码写于App.vue页面,相当于全局监听,每个路由是被包含在div中的!

<template>
  <div id="app"  @click="clickDiv">
    <router-view></router-view>
  </div>
</template>
<script>
export default {
  name: "App",
  data() {
    return {
      lastTime: null, // 最后一次点击的时间
      currentTime: null, // 当前点击的时间
      timeOut: 10 * 60 * 1000, // 设置超时时间:10分钟
      timeInterval: "",
    };
  },
  methods: {
    clickDiv() {
      if (this.timeInterval == "") {
       // 5秒钟检测一次
        this.timeInterval = setInterval(this.isTimeOut, 5000);
      }
      this.lastTime = new Date().getTime();
    },
    isTimeOut() {
      this.currentTime = new Date().getTime(); // 当前时间
      // 判断上次最后一次点击的时间和这次点击的时间间隔是否大于规定的时间,例:10分钟
      if (this.currentTime - this.lastTime > this.timeOut) {
        //判断是否为登录状态,只有登录状态下才调用方法
        if (sessionStorage.token) {
          sessionStorage.clear();
          clearInterval(this.timeInterval);
          this.timeInterval = "";
          this.$router.push({
            name: "login",
          });
          //先返回首页,在给提示,可以根据具体需求调整
          this.$alert("检测到您长时间未操作页面,请重新登录!", "温馨提示", {
            confirmButtonText: "确定",
            callback: (action) => {},
          });
        }
      }
    },
  },
};
</script>
posted @ 2024-04-01 16:50  CoderI  阅读(72)  评论(0编辑  收藏  举报