LocalStorage.js
function localset(key, val, expire) {
var exp = expire ? Date.now() + expire * 1000 : -1;
localStorage.setItem(key, JSON.stringify({value: val, expire: exp}));
console.log('set ok', JSON.stringify({value: val, expire: exp}));
}
function localget(key) {
var data = localStorage.getItem(key);
if (!data) return null;
var dataObj = JSON.parse(data);
if (dataObj.expire == -1) return dataObj.value;
if (Date.now() >= dataObj.expire) {
localStorage.removeItem(key);
return null;
} else {
return dataObj.value;
}
}
export {localset,localget}
使用测试
//设置localStorage
localset("user",JSON.stringify(this.users),1800);//设置key为user,值为json字符串,时间为30分钟
//获取localStorage
var user=JSON.parse(localget("user"));获取user;