创建 src/utils/Storage.ts 文件
/**
* 创建本地缓存对象
* @param {string} prefixKey 键的前缀
* @param {Storage} storage 缓存的类型;可以是 localStorage 和 sessionStorage; 默认: localStorage;
*/
export const createStorage = (prefixKey: string = '', storage: Storage = localStorage) => {
// 本地缓存类
const Storage = class {
private storage = storage
private prefixKey?: string = prefixKey
/**
* @description 获取缓存的键
* @param {string} key 缓存键
* @return {string} 缓存的键
*/
private getKey(key: string) {
return `${this.prefixKey}${key}`.toUpperCase()
}
/**
* @description 设置缓存
* @param {string} key 缓存键
* @param {any} value 缓存值
* @param { number | null} expire 缓存有效期,单位: s;
*/
set(key: string, value: any, expire: number | null = null) {
const stringData = JSON.stringify({
value,
expire: expire !== null ? new Date().getTime() + expire * 1000 : null,
})
this.storage.setItem(this.getKey(key), stringData)
}
/**
* 读取缓存
* @param {string} key 缓存键
* @param {any} defaultValue 默认值, 当从本地读取不到值时,返回此默认值;默认: null;
*/
get<T = any>(key: string, defaultValue: any = null): T | null {
const item = this.storage.getItem(this.getKey(key))
if (item) {
try {
const data = JSON.parse(item)
const { value, expire } = data
// 在有效期内直接返回
if (expire === null || expire >= Date.now()) {
return value
}
this.remove(this.getKey(key))
} catch (e) {
console.error(e)
return defaultValue
}
}
return defaultValue
}
/**
* 从缓存删除某项
* @param {string} key 缓存键
*/
remove(key: string) {
this.storage.removeItem(this.getKey(key))
}
/**
* 清空所有缓存
*/
clear(): void {
this.storage.clear()
}
/**
* 设置cookie
* @param {string} name cookie 名称
* @param {*} value cookie 值
* @param {number=} expire 过期时间
* 如果过期时间为设置,默认关闭浏览器自动删除
*/
setCookie(name: string, value: any, expire: number | null = null) {
document.cookie = `${this.getKey(name)}=${value}; Max-Age=${expire}`
}
/**
* 根据名字获取 cookie 值
* @param {string} name cookie 名称
*/
getCookie(name: string): string {
const cookieArr = document.cookie.split('; ')
for (let i = 0, length = cookieArr.length; i < length; i++) {
const kv = cookieArr[i].split('=')
if (kv[0] === this.getKey(name)) {
return kv[1]
}
}
return ''
}
/**
* 根据名字删除指定的 cookie
* @param {string} key 缓存键
*/
removeCookie(key: string) {
this.setCookie(key, 1, -1)
}
/**
* 清空cookie,使所有cookie失效
*/
clearCookie(): void {
const keys = document.cookie.match(/[^ =;]+(?==)/g)
if (keys) {
for (let i = keys.length; i--;) {
document.cookie = `${keys[i]}=0;expire=${new Date(0).toUTCString()}`
}
}
}
}
// 返回一个实例化后的本地缓存类
return new Storage()
}
export const Storage = createStorage()
export default Storage