localstorage原本是不带过期时间的,xijs提供了一个带过期时间封装的store工具,但是用起来因为文档基本等于没有,所以干脆直接封装一个用,其中ttl是过期时间,以毫秒计算。
// 设置
function setLocalStorageWithExpiry(key, value, ttl) {
const now = new Date()
// ttl : 毫秒
const item = {
value: value,
expiry: now.getTime() + ttl,
}
localStorage.setItem(key, JSON.stringify(item))
}
// 获取value
function getLocalStorageWithExpiry(key) {
const itemValue = localStorage.getItem(key)
if (!itemValue) {
return null
}
const item = JSON.parse(itemValue)
const now = new Date()
if (now.getTime() > item.expiry) {
localStorage.removeItem(key)
return null
}
return item.value
}
// 删除过期的所有key
function batchRemoveExpiredKeys() {
const keys = Object.keys(localStorage);
// 过滤出过期的key
const expiredKeys = keys.filter(key => {
const value = localStorage.getItem(key);
try {
const data = JSON.parse(value);
return data.expirey && Date.now() > data.expirey;
} catch (e) {
return false;
}
});
// 删除过期的key
expiredKeys.forEach(key => {
localStorage.removeItem(key);
});
}