localStorage 设置过期时间
需求:登录,校验通过后生成token,默认6小时失效,若记住登录状态则30天内有效一、封装localStorageSet函数localStorageSet(name, data, expire){const obj = {data,expire};localStorage.setItem(name, JSON.stringify(obj));}二、函数调用let expire =new Date(
·
需求:登录,校验通过后生成token。若登录状态没勾选时6小时失效,若登录状态勾选则30天内有效
一、封装localStorageSet函数
localStorageSet(name, data, expire){
const obj = {
data,
expire
};
localStorage.setItem(name, JSON.stringify(obj));
}
二、函数调用
//let expire = new Date().getTime() + 60 * 60 * 1000; // 延迟1小时后的微秒
if(_this.obj.checked == false){ //登录状态没有勾选,默认6小时失效
let expire = new Date().getTime() + 60 * 60 * 1000 * 6; // 延迟6小时后的微秒
_this.localStorageSet('token', {
token:res.data.token
}, expire);
}else{ //登录状态勾选 ,30天内有效
let expire = new Date().getTime() + 60 * 60 * 1000 * 24 * 30; // 延迟30天后的微秒
_this.localStorageSet('token', {
token:res.data.token
}, expire);
}
三、再次到登录页面时,读取缓存
//读取缓存
var jsonParse = JSON.parse(localStorage.getItem("token")); //获取缓存对象
const time = new Date().getTime(); //获取当前时间的时间戳
if(jsonParse){
console.log(jsonParse.expire) //存在localStorage的微秒数
if(time < jsonParse.expire){ //当前时间的微秒小于 localStorage的微秒,即token存在,则跳转到数据概览页
this.$router.push({path:'/internalUsers/businessOverview/businessOverview/patentPage'})
}else{ //否则,token失效,清除本地缓存,留在登录页面。
localStorage.removeItem('token');
}
}
更多推荐
所有评论(0)