使用 mouseover 事件来监测是否有用户操作页面,写一个定时器间隔特定时间检测是否长时间未操作页面,如果是,退出登陆,清除token,返回登录页
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(e) {}
return value || defaultValue
},
removeItem(key) {
window.localStorage.removeItem(key)
},
clear() {
window.localStorage.clear()
},
}
2.在util文件夹下创建一个astrict.js
// 引入路由和storage工具函数
import storage from '@/utils/storage'
import router from "@/common/router"
let lastTime = new Date().getTime()
let currentTime = new Date().getTime()
let timeOut = 30 * 60 * 1000 //设置超时时间: 30分钟
window.onload = function () {
window.document.onmousedown = function () {
stroage.setItem("lastTime", new Date().getTime())
}
};
function checkTimeout() {
if(router.currentRouter.name === 'login') return // 当前已经是登陆页时不做跳转
//if(router.currentRouter.fullPath === '/login') return // 当前已经是登陆页时不做跳转
currentTime = new Date().getTime() //更新当前时间
lastTime = storage.getItem("lastTime");
if (currentTime - lastTime > timeOut) { //判断是否超时
// 清除storage的数据(登陆信息和token)
storage.clear()
// 跳到登陆页
router.push({ name: 'login' })
//router.push('/login')
}
}
export default function astrict () {
/* 定时器 间隔30秒检测是否长时间未操作页面 */
window.setInterval(checkTimeout, 30000);
}
3.在main.js引入astrict.js
import Astrict from '@/utils/astrict'
Vue.use(Astrict)