前端无操作一段时间返回登录页

项目场景:

公司项目需求要求页面无操作三十分钟之后就自动返回到登录页。

解决方案:

项目使用的vue技术,所以我是在App.vue添加

复制代码
<template>
  <div id="app">
    <router-view />
  </div>
</template>
<script>
export default {
  data() {
    return {
      //设置超时时间: 30分种
      timeOut: 30 * 60 * 1000,
    }
  },
  methods: {
    // 存储当前时间
    setLastTime() {
      localStorage.setItem('lastTime', new Date().getTime());
    },
    // 获取时间
    getLastTime() {
      return localStorage.getItem('lastTime');
    },
    checkTimeout() {
      // 登录页面不监听
      if (this.timeOut && this.$router.currentRoute.name === 'login') {
        this.setLastTime();
      }
      else {
        //更新当前时间
        let currentTime = new Date().getTime();
        let lastTime = this.getLastTime();
        //判断是否超时
        if (currentTime - lastTime > this.timeOut) {
          this.$router.push('/login');
          this.$message({ type: 'warning', message: '长时间未操作,需重新登录' })
          document.title='登录页'
          localStorage.removeItem("Authorization");
        }
      }
    },
  },
  mounted() {
    let that = this;
    // 每30秒 调用检查时间的方法
    this.$nextTick(function () {
      setInterval(this.checkTimeout, 30000);
    })
    // 页面监听 按下鼠标更新操作时间
    window.onload = function () {
      window.document.onmousedown = function () {
        that.setLastTime();
      }
    };
  }
};
</script>
<style>
html,
body,
#app {
  height: 100%;
  width: 100%;
  padding: 0;
  margin: 0;
  margin-top: 0;
}
</style>

注意:这样可能会出现一登录之后由于没有马上点击页面导致马上返回到导航舱,所以需要在封装请求那里,一旦接口返回就刷新lastTime

复制代码
localStorage.setItem('lastTime', new Date().getTime());
相关推荐
独角鲸网络安全实验室几秒前
2026微信小程序抓包全解析:从实操落地到合规风控,解锁前端调试新范式
前端·微信小程序·小程序·抓包·系统代理绕过·https证书严格校验·进程隔离
紫微AI几秒前
前端文本测量成了卡死一切创新的最后瓶颈,pretext实现突破了
前端·人工智能·typescript
GISer_Jing1 分钟前
AI前端(From豆包)
前端·aigc·ai编程
IT枫斗者1 分钟前
前端部署后如何判断“页面是不是最新”?一套可落地的版本检测方案(适配 Vite/Vue/React/任意 SPA)
前端·javascript·vue.js·react.js·架构·bug
测试修炼手册1 分钟前
[测试技术] 深入理解 JSON Web Token (JWT)
前端·json
AI老李3 分钟前
2026 年 Web 前端开发的 8 个趋势!
前端
里欧跑得慢5 分钟前
15. Web可访问性最佳实践:让每个用户都能平等访问
前端·css·flutter·web
钛态5 分钟前
前端趋势:别被时代抛弃
前端·vue·react·web
小码哥_常24 分钟前
Room 3.0:移动端持久化的“重生”变革
前端
九转成圣1 小时前
Java 性能优化实战:如何将海量扁平数据高效转化为类目字典树?
java·开发语言·json