1. 创建一个公共js文件
import router from '../router'
import store from '../store'
var lastTime = new Date().getTime()
var currentTime = new Date().getTime()
var timeOut = 10 * 60 * 1000 // 设置超时时间: 10分 随意设置
window.onload = function() {
window.document.onmousedown = function() {
localStorage.setItem('lastTime', new Date().getTime())
}
}
function checkTimeout() {
currentTime = new Date().getTime() // 更新当前时间
lastTime = localStorage.getItem('lastTime')
// console.log(currentTime - lastTime);
// console.log(timeOut);
if (currentTime - lastTime > timeOut) { // 判断是否超时 ,在这里面写退出的一些操作
// console.log("超时");
// var url = window.location.href
// var newUrl = url.match(/(\S*)#/)[1]
// window.open(newUrl + '#/login', '_self')
logout() //本人项目中的退出方法
}
}
//退出方法
async function logout() {
await store.dispatch('user/logout')
router.push(`/login?redirect=${this.$route.fullPath}`)
}
/* 定时器 间隔30秒检测是否长时间未操作页面 */
window.setInterval(checkTimeout, 30000)
2. 如何使用
在 vue 项目中的main.js中引入这个js文件即可
注意: 在登陆的时候需要先向localStorage里面更新下登陆时间,以此时间来监听是否位未操作时间到期
window.localStorage.setItem(‘lastTime’, new Date().getTime())
这个适用于其他的框架,方法之类的稍微修改即可,主要思路类似
判断鼠标有多久未改变位置,在通过这个时间去对比是否超时