思路:设置两个时间,一个是更新鼠标移动时(lastTime),另一个是获取现在的时间(currentTime),再将两者对比 设置currentTime超出lastTime多长时间 执行跳转登录页即可
// 文件名:astrict.js
let lastTime = new Date().getTime()
let currentTime = new Date().getTime()
const timeOut = 30 * 60 * 1000 // 设置超时时间: 30分钟
let timeRunning
window.onload = function () {
window.document.onmouseover = function () {
lastTime = new Date().getTime() // 更新lastTime
}
}
function checkTimeout () {
currentTime = new Date().getTime() // 更新当前时间
if (currentTime - lastTime > timeOut) { // 判断是否超时
// 清除定时
clearInterval(timeRunning)
// 清除缓存
window.localStorage.clear()
// 跳到登陆页
/* 跳转代码 */
}
}
export default function () {
timeRunning = window.setInterval(checkTimeout, 30 * 1000) // 设置监测时间:30s/次
}
最后在需要调用的页面import再引用就OK啦
import Astrict from '@/utils/astrict'
Astrict() // 登出超时判断