需求:实现单页长时间不操作自动退出登录清除token,返回登录页
根据需求的思路是:每次操作页面时候存储当前时间,当前时间与存储时间比较,是否超过设定的时间,超过就退出登录,返回登录页
第一步:在until文件夹中新建 astrict.js
//单页长时间不操作就会自动退出
var lastTime = new Date().getTime()
var currentTime = new Date().getTime()
var timeOut = 1 * 60 *1000 //设置超时时间: 30分
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*)#/);
console.log(newUrl);
sessionStorage.clear()
window.open('/login','_self');
}
}
/* 定时器 间隔30秒检测是否长时间未操作页面 */
window.setInterval(checkTimeout, 30000);
第二步:在main.js 中导入
import Astrict from './assets/js/astrict.js'
Vue.use(Astrict)
根据以上操作即可实现该需求。。。。