vue设置页面超时15分钟自动退出登录

需求:用户登录后,如果长时间未操作页面这个时候需要自动退出登录回到登录页面。

注意点:这里我们如果把超时的时间放到浏览器里面存储,我们要放到本地存储里面localStorage里面

Vue设置长时间未操作登录以后自动到期返回登录页

方法一:

在app.vue中添加点击事件,并且点击时候添加点击的时间,这里我们进行判断是否超时情况

Vue2里面的使用

javascript 复制代码
<template>
  <!-- 添加点击事件 -->
  <div id="app" style="height: 100%" @click="isTimeOut">
    <router-view/>
  </div>
</template>

<script>
export default {
  name: 'App',

  data () {
    return {
      lastTime: null, // 最后一次点击的时间
      currentTime: null, // 当前点击的时间
      timeOut: 15 * 60 * 1000 // 设置超时时间:30分钟
    }
  },
  created () {
    this.lastTime = new Date().getTime()
  },
  methods: {
    isTimeOut () {
      this.currentTime = new Date().getTime() // 记录这次点击的时间
      if (this.currentTime - this.lastTime > this.timeOut) { // 判断上次最后一次点击的时间和这次点击的时间间隔是否大于30分钟
        if (localStorage.getItem('loginInfo')) { // 如果是登录状态
          localStorage.clear()
          sessionStorage.clear();
          this.$router.push({name: 'login'})
        } else {
          this.lastTime = new Date().getTime()
        }
      } else {
        this.lastTime = new Date().getTime() // 如果在30分钟内点击,则把这次点击的时间记录覆盖掉之前存的最后一次点击的时间
      }
    }
  }
}
</script>
方法二:

Vue3里面应用:

在路由ruouter路由加载后进行判断是否有超时的逻辑

具体引用如下:

在utils里面创建点击是否超时的组件如下activeCheck.ts

javascript 复制代码
import { Local, Session } from "./storage"
import router from '/@/router';
const timeOut = 15 * 60 * 1000; //设置超时时间: 15分

function updateActiveTime() {
  localStorage.setItem('lastActiveTime', new Date().getTime() + '');
}

window.onload = function () {
  window.document.onmousedown = updateActiveTime;
};

let checkActiveInterval: any = null

export const startActiveCheck = () => {
  if (checkActiveInterval !== null) return
  updateActiveTime();
  checkActiveInterval = setInterval(() => {
    const currentTime = new Date().getTime();
    const lastActiveTime = localStorage.getItem('lastActiveTime');
    if (currentTime - Number(lastActiveTime) > timeOut) {
      Local.clear();
      Session.clear();
      clearInterval(checkActiveInterval)
      checkActiveInterval = null
      router.push('/login');
    }
  }, 30000);
}

export const endActiveCheck = () => {
  clearInterval(checkActiveInterval)
  checkActiveInterval = null
}

这里的storage.ts存储组件如下:

javascript 复制代码
import Cookies from 'js-cookie';

/**
 * window.localStorage 浏览器永久缓存
 * @method set 设置永久缓存
 * @method get 获取永久缓存
 * @method remove 移除永久缓存
 * @method clear 移除全部永久缓存
 */
export const Local = {
	// 查看 v2.4.3版本更新日志
	setKey(key: string) {
		// @ts-ignore
		return `${__NEXT_NAME__}:${key}`;
	},
	// 设置永久缓存
	set<T>(key: string, val: T) {
		window.localStorage.setItem(Local.setKey(key), JSON.stringify(val));
	},
	// 获取永久缓存
	get(key: string) {
		let json = <string>window.localStorage.getItem(Local.setKey(key));
		try{
			return JSON.parse(json);
		}catch{
			return json
		}
	},
	// 移除永久缓存
	remove(key: string) {
		window.localStorage.removeItem(Local.setKey(key));
	},
	// 移除全部永久缓存
	clear() {
		window.localStorage.clear();
	},
};

/**
 * window.sessionStorage 浏览器临时缓存
 * @method set 设置临时缓存
 * @method get 获取临时缓存
 * @method remove 移除临时缓存
 * @method clear 移除全部临时缓存
 */
export const Session = {
	// 设置临时缓存
	set<T>(key: string, val: T) {
		window.sessionStorage.setItem(Local.setKey(key), JSON.stringify(val));
	},
	// 获取临时缓存
	get(key: string) {
		let json = <string>window.sessionStorage.getItem(Local.setKey(key));
		return JSON.parse(json);
	},
	// 移除临时缓存
	remove(key: string) {
		window.sessionStorage.removeItem(Local.setKey(key));
	},
	// 移除全部临时缓存
	clear() {
		window.sessionStorage.clear();
	},
};
javascript 复制代码
import { endActiveCheck, startActiveCheck } from '../utils/activeCheck';
// 路由加载后
router.afterEach((to) => {
  NProgress.done();
  if (to.path === '/login') {
    endActiveCheck()
  } else {
    startActiveCheck()
  }
});
相关推荐
vipbic4 分钟前
中后台越做越乱后,我用插件化把它救回来了
前端·vue.js
Hyyy9 分钟前
Computer Use 适合做什么,不适合做什么——一次真实使用后的思考
前端
小和尚同志36 分钟前
前端 AI 单元测试思考与落地
前端·人工智能·aigc
invicinble2 小时前
c端系统,其实更像一个信息展示平台
前端
李姆斯3 小时前
管理是否可以被完全量化
前端·产品经理·团队管理
名字还没想好☜3 小时前
Next.js 中间件实战:鉴权、重定向与 A/B 分流
开发语言·前端·javascript·中间件·react·next.js
广州灵眸科技有限公司3 小时前
瑞芯微RV1126B开发板(EASY-EAI-PI2) INI文件操作
java·前端·javascript·网络·人工智能
江华森4 小时前
Web 开发基础:HTTP 与 REST
前端·网络协议·http
IT_陈寒5 小时前
Redis的KEYS命令把我搞崩溃了,改用SCAN才活过来
前端·人工智能·后端
Jackson__5 小时前
为什么 Agent 越聊越慢?聊聊 Context(上下文)管理
前端·agent·ai编程