localStorage如何设置过期时间 (如何封装自定义localStorage)

1、创建Storage类

  • 定义 对应的get set remove clear api
  • 通过set函数添加过期时间参数来实现过期时间的记录
  • 设置存储时存储当前值和过期时间
  • get取值的时候先验证当前值是否存在 以及时间是否大于过期时间 如果存在且不大于过期时间既可返回对应的值否则返回空
复制代码
class Storage {
    constructor() {
        this.storageName = 'expiredStorage'
    }
    
    
    /**
     *  设置缓存
     *  @param {string} name 缓存名称
     *  @param {any} value 缓存的值
     *  @param {any} expires 缓存过期时间(秒) 
    **/
    set(name, value, expires) {
        const storages ={}
        storages[name] = {
            value,
            expires: storages[name]
                ? storages[name].expires
                : expires === undefined
                ? +new Date() + 31536000000 //默认365天 这个值可以自己修改
                : expires * 1000 + +new Date(),
        };
        localStorage.setItem(this.storageName, JSON.stringify(storages))
    }
    
    /**
     *  获取缓存
     *  @param {string} name 缓存名称
    **/
    get(name) {
        const storages = JSON.parse(localStorage.getItem(this.storageName))
        try {
            if (!storages[name]) {
                // 不存在
                return null;
            }
            console.log('log=====',  storages[name].expires - new Date());
            if (+new Date() > storages[name].expires) {
                // 存在但过期
                this.remove(name);
                return null;
            }
            return storages[name].value;
        } catch (error) {
            console.log('[ControlStorage] the error message: get field failed\n', error);
        }
    }
    
   /**
     *  移除对应缓存
     *  @param {string} name 缓存名称
    **/
    remove(name) {
        const storages = JSON.parse(localStorage.getItem(this.storageName))
        try {
            delete storages[name];
            if (JSON.stringify(storages) === '{}') {
            // 缓存字段为空对象时,删除该字段
            this.clear();
            return;
        }
        this.baseStorage.setItem(storages);
        } catch (error) {
            console.log('[ControlStorage] the error message: remove field failed\n', error);
        }
    }
    /**
     *  清除所有带过期时间的缓存
    **/
    clear() {
        localStorage.removeItem(this.storageName)
    }
}

export default new Storage();
复制代码

2、实际调用 引入对应的Storage类 调用里面的方法传递对应参数

复制代码
import storage from './js/storage.js'

...
setStorage() {
    // 5秒过期
    storage.set('name', 'ghkmmm', 5)
},
getStorage() {
    console.log(storage.get('name'))
},
removeStorage() {
    storage.remove('name')
},
复制代码

 

posted @   有只小菜猫  阅读(618)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
点击右上角即可分享
微信分享提示