vue实现用户长时间不操作,提示用户登录已过期请重新登录
1.实现思路
使用 mouseover事件来监测是否有用户操作页面,然后写一个定时器间隔特定时间检测是否长时间未操作页面,如果是清除token,提示登录已过期请重新登录
2.实现代码
1.在util文件夹下创建一个storage.js封装localStorage方法
export default {
setItem(key, value) {
value = JSON.stringify(value);
window.localStorage.setItem(key, value)
},
getItem(key, defaultValue) {
let value = window.localStorage.getItem(key)
try {
value = JSON.parse(value);
} catch {}
return value || defaultValue
},
removeItem(key) {
window.localStorage.removeItem(key)
},
clear() {
window.localStorage.clear()
},
}
2.在util文件夹下创建一个testing.js
每隔10s去检查一下用户是否过了15分钟未操作页面
因为我这边是单点登录所以用户15分钟未操作就要跳转到单点登录系统,所以跳转这一块按实际情况来修改
import storage from '@/utils/storage'
// 导入cookie工具(这边需要自己按需求封装)
import {PcCookie,Key} from '@/utils/cookie'
let lastTime = new Date().getTime()
let currentTime = new Date().getTime()
let timeOut = 15 * 60 * 1000 //设置超时时间: 15分钟
window.onload = function () {
window.document.onmousedown = function () {
// 保存最新的操作时间到storage中
storage.setItem("lastTime", new Date().getTime())
}
};
function checkTimeout() {
//更新当前时间
currentTime = new Date().getTime()
lastTime = storage.getItem("lastTime");
//判断是否超时
if (currentTime - lastTime > timeOut) {
// 清除storage的数据(登陆信息和token)
storage.clear()
// 移除cookie
PcCookie.remove(Key.accessTokenKey)
PcCookie.remove(Key.userInfoKey)
// 401 未认证或者访问令牌过期,未认证则要通过刷新令牌获取新的认证信息
let isLock = true // 防止重复发送刷新请求
if(isLock && PcCookie.get(Key.refreshTokenKey)) {
isLock = false // 在发送后,将此值 设置为false
// 跳转到认证中心客户端,实现刷新令牌效果
window.location.href = `${process.env.VUE_APP_AUTH_CENTER_URL}/refresh?redirectURL=${window.location.href}`
}else {
//没有刷新令牌,则跳转到认证客户端进行重新认证
window.location.href = `${process.env.VUE_APP_AUTH_CENTER_URL}?redirectURL=${window.location.href}`
}
}
}
export default function () {
/* 定时器 间隔10秒检测是否长时间未操作页面 */
window.setInterval(checkTimeout, 10000);
}
3.在main.js引入testing.js
import Testing from '@/utils/testing'
Vue.use(Testing )
3.实现效果