vue 前端判断用户长时间未操作退出功能

需求描述:需要前端判断半小时没有操作退出登录功能

思路:拿到点击的最新时间 减去上次的时间 如果大于设置的时间就退出登录

<template>
  <div id="app" style="height: 100%" @click="isTimeOut">
    <router-view></router-view>
  </div>
</template>
 
  data() {
    return {
      lastTime: null, // 最后一次点击的时间
      currentTime: null, // 当前点击的时间
      timeOut: 1 * 60 * 60 * 1000, // 1小时
    };
  },
  
  created() {
    // 打开页面时,记录第一次的时间
    this.lastTime = new Date().getTime();
  },
 
  methods: {
    // 点击超时的点击事件
    isTimeOut() {
      // 记录最新一次的点击的时间
      this.currentTime = new Date().getTime();
 
      if (this.currentTime - this.lastTime > this.timeOut) {
        // 判断上次最后一次点击的时间和这次点击的时间间隔是否超时 timeOut 此处超时
        if (localStorage.getItem("xxx")) {
          // 如果是登录状态有xxx情况下,清除localStorage和sessionStorage,并跳转到登录页
          localStorage.clear();
          sessionStorage.clear();
 
          // 弹窗提示
          this.$alert("您已长时间未操作,系统自动退出!请重新登录!", "警告", {
            confirmButtonText: "确定",
            callback: () => {
              this.$router.push("/login");
            },
          });
        } else {
          // 如果是未登录状态,则更新最后点击的时间
          this.lastTime = new Date().getTime();
        }
      } else {
        // 此处没超时,则更新最后点击的时间
        this.lastTime = new Date().getTime();
      }
    },
  }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值