localStorage设置过期时间
步骤:
- 在存储原始数据时附带上过期时间
- 查询数据时,将当前时间与存储的过期时间进行比较
- 如果当前时间大于存储的过期时间,则返回null并从存储中删除该条数据,否则,返回原始信息。
// 这里 expired过期时间单位为 分钟
const storage = {
setItem: function (key: string, value: any, expired?: number) {
let data = expired ? { value, expired: Date.now() + expired * 60 * 1000 } : { value };
localStorage.setItem(key, JSON.stringify(data));
},
getItem: function (key: string) {
if (!localStorage.getItem(key)) return;
let data = JSON.parse(localStorage.getItem(key) || '');
if (data.expired && Date.now() > data.expired) {
this.removeItem(key);
return;
}
return data.value;
},
removeItem: function (key: string) {
localStorage.removeItem(key);
},
clear: function () {
localStorage.clear();
}
};
export default storage;