当前位置:首页 > 编程笔记 > 正文
已解决

带过期时间的localstorage封装

来自网友在路上 156856提问 提问时间:2023-10-27 08:11:17阅读次数: 56

最佳答案 问答题库568位专家为你答疑解惑

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))}
// 获取valuefunction 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}
// 删除过期的所有keyfunction batchRemoveExpiredKeys() {const keys = Object.keys(localStorage);// 过滤出过期的keyconst 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;}});// 删除过期的keyexpiredKeys.forEach(key => {localStorage.removeItem(key);});}

查看全文

99%的人还看了

猜你感兴趣

版权申明

本文"带过期时间的localstorage封装":http://eshow365.cn/6-25844-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!