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

项目场景:

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

解决方案:

项目使用的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());
相关推荐
chillxiaohan几秒前
GO学习记录——多文件调用
开发语言·学习·golang
2301_822366355 分钟前
C++中的命令模式变体
开发语言·c++·算法
一刻钟.7 分钟前
C#高级语法之线程与任务
开发语言·c#
追逐梦想的张小年21 分钟前
JUC编程03
java·开发语言·idea
-凌凌漆-21 分钟前
【vue】选项式api与组合式api
前端·javascript·vue.js
派葛穆23 分钟前
Python-PyQt5 安装与配置教程
开发语言·python·qt
2601_9498095923 分钟前
flutter_for_openharmony家庭相册app实战+通知设置实现
android·javascript·flutter
小乔的编程内容分享站31 分钟前
记录使用VSCode调试含scanf()的C语言程序出现的两个问题
c语言·开发语言·笔记·vscode
toooooop842 分钟前
php BC MATH扩展函数计算精度-第三个参数
开发语言·php
蓁蓁啊1 小时前
C/C++编译链接全解析——gcc/g++与ld链接器使用误区
java·c语言·开发语言·c++·物联网