localStorage实现7天登录过期
实现原理:存localStorage比较初始登录时存在缓存的时间戳和现在进入页面的时间戳,然后用sessionStorage去判断不勾选但是登录了的状态
精简版
function isPastDue() {
// 过期时间7天
var time = 604800000; //1000*60*60*24*7;
var storage = window.localStorage;
var oldTimestamp = storage.getItem('timestamp');//以前存的时间戳
if (oldTimestamp){
var nowTimestamp = new Date().getTime();//当前时间戳
// 如果当前时间戳> 前面存的时间戳+过期时间 表示已经过期
var sumTimestamp = timestamp + time;
if (nowTimestamp > sumTimestamp) {
storage.clear();
}
}
}
完整版:
//1、点击了登录成功后的回调函数里
var localStorage = window.localStorage;
var sessionStorage = window.sessionStorage;
var userInfo = res.data.data[0];
if(that.checkBox){//如果勾选了7天
localStorage.setItem("timestamp", new Date().getTime());
sessionStorage.setItem('greenPath',1);
}else{
sessionStorage.setItem('greenPath',0);
}//2、在main.js的router.beforeEach里
// 7天登录
function isPastDue() {
// 过期时间7天
var time = 604800000; //1000*60*60*24*7;
var storage = window.localStorage;
if (storage.getItem('timestamp')){
var oldTimestamp = storage.getItem('timestamp');//以前存的时间戳
var nowTimestamp = new Date().getTime();//当前时间戳
// 如果当前时间戳> 前面存的时间戳+过期时间 表示已经过期
var sumTimestamp = oldTimestamp + time;
if (nowTimestamp > sumTimestamp) {
storage.clear();
}
}else{
if (sessionStorage.getItem('greenPath')==0) {
return false;
}else{
storage.clear();
}
}
}