网站建设营销企业,ux与ui设计的区别,海北高端网站建设价格,联想公司网站建设现状cache.ts缓存工具 浏览器缓存工具封装实现使用方法示例代码 浏览器缓存工具封装
在前端开发中#xff0c;经常会遇到需要缓存数据的情况#xff0c;例如保存用户的登录状态、缓存部分页面数据等
但有时候需要缓存一些复杂的对象#xff0c;例如用户信息对象、设置配置等。… cache.ts缓存工具 浏览器缓存工具封装实现使用方法示例代码 浏览器缓存工具封装
在前端开发中经常会遇到需要缓存数据的情况例如保存用户的登录状态、缓存部分页面数据等
但有时候需要缓存一些复杂的对象例如用户信息对象、设置配置等。直接使用原生浏览器缓存API存储这些对象时需要手动进行JSON序列化和反序列化操作过程相对繁琐为了方便管理和操作浏览器的本地缓存和会话缓存所以封装一个通用的工具类来处理这些操作
实现
创建了一个名为Cache的工具类该类具有以下方法 constructor(type: CacheType): 构造函数根据传入的CacheType参数选择使用localStorage还是sessionStorage作为底层存储。setCache(key: string, value: any): 将指定的键值对存储到缓存中。如果value不为空则将其转换为JSON字符串并存储。getCache(key: string): 根据键获取缓存中存储的值。如果值存在则将其解析为对应的JSON对象并返回。removeCache(key: string): 根据键从缓存中移除相应的数据。clear(): 清空缓存中的所有数据。 定义了一个枚举类型CacheType用于表示缓存类型包括Local和Session。
使用方法示例
import { localCache, sessionCache } from cache.ts;// 存储数据到本地缓存
localCache.setCache(username, John Doe);
sessionCache.setCache(isLoggedIn, true);// 从本地缓存获取数据
const username localCache.getCache(username); // John Doe
const isLoggedIn sessionCache.getCache(isLoggedIn); // true// 移除数据
localCache.removeCache(username);
sessionCache.removeCache(isLoggedIn);// 清空整个缓存
localCache.clear();
sessionCache.clear();使用案例代码解析 首先直接导入了封装的cache.ts工具类中的localCache和sessionCache实例。这些实例已经预先配置好了无需再次手动构造。 接下来通过调用setCache方法向本地缓存和会话缓存中存储数据。例如我们使用localCache.setCache(‘username,John Doe’)将用户名信息存储到本地缓存中sessionCache.setCache(‘isLoggedIn’, true)将登录状态存储到会话缓存中。 然后通过调用getCache方法从缓存中获取数据。例如使用localCache.getCache(‘username’)可以获取存储在本地缓存中的用户名信息并将其赋值给变量username。类似地使用sessionCache.getCache(‘isLoggedIn’)可以获取存储在会话缓存中的登录状态并赋值给变量isLoggedIn。 如果需要移除特定的缓存数据可以使用removeCache方法。通过传入相应的键例如localCache.removeCache(username)我们可以将存储在本地缓存中的用户名信息移除。 如果希望清除整个缓存可以使用clear方法。例如通过调用localCache.clear()可以清空本地缓存中的所有数据。类似地使用sessionCache.clear()可以清空会话缓存。 代码
enum CacheType {Local,Session
}class Cache {storage: Storageconstructor(type: CacheType) {this.storage type CacheType.Local ? localStorage : sessionStorage}setCache(key: string, value: any) {if (value) {this.storage.setItem(key, JSON.stringify(value))}}getCache(key: string) {const value this.storage.getItem(key)if (value) {return JSON.parse(value)}}removeCache(key: string) {this.storage.removeItem(key)}clear() {this.storage.clear()}
}const localCache new Cache(CacheType.Local)
const sessionCache new Cache(CacheType.Session)export { localCache, sessionCache }