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

发布时间 2023-06-22 17:08:04作者: 有只小菜猫

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')
},