import store from '@/store'
import { getToken } from "@/utils/auth";
import { MessageBox } from 'element-ui'
export default function () {
let setInterval = null;//定时器
let timeOut = 60 * 1000 * 60// 设置超时时间: 1小时
// let timeOut = 10 * 1000 // 设置超时时间: 1小时
// console.log("开始", new Date().getTime())
// 初次向sessionStorage存入操作时间
window.sessionStorage.setItem('lastTime', new Date().getTime())
// 每次操作页面,更新sessionStorage存入的操作时间
window.onload = function () {
window.document.onmousedown = function () {
console.log("开始")
window.sessionStorage.setItem('lastTime', new Date().getTime())
}
}
MessageBox.setDefaults({
closeOnClickModal: false
})
function checkTimeout() {
let currentTime = new Date().getTime() // 当前时间
let lastTime = window.sessionStorage.getItem("lastTime")//上次操作的时间
// 判断是否超时
if(getToken()){
if (currentTime - lastTime >= timeOut) {
MessageBox(
'登录状态已过期,请重新登录',
'系统提示', {
confirmButtonText: '重新登录',
closeOnClickModal: false,
type: 'warning'
}
).then(() => {
store.dispatch('LogOut').then(() => {
location.reload() // 为了重新实例化vue-router对象 避免bug
})
// 清除定时器
window.clearInterval(setInterval);
// 清除sessionStorage
window.sessionStorage.clear('lastTime')
})
}
}
}
/* 定时器 间隔2秒检测是否长时间未操作页面 */
setInterval = window.setInterval(checkTimeout, 30000)
// setInterval = window.setInterval(checkTimeout, 10000)
}
在main.js中引用并使用