enum CacheType {
Local,
Session
}
class Cache {
storage: Storage
constructor(type: CacheType) {
this.storage = type === CacheType.Local ? localStorage : sessionStorage
}
setCache(key: string, value: any) {
if (value!==undefined) {
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)
}
clearCache() {
this.storage.clear()
}
}
const localCache = new Cache(CacheType.Local)
const sessionCache = new Cache(CacheType.Session)
export { localCache, sessionCache }
因为JSON.stringif和JSON.parse都不能传空值,所以为了不用每次都判断一下,进行了封装
使用:
import { localCache } from '/@/utils/cache/cache'
function handleRememberMe() {
isRememberMe.value = !isRememberMe.value
localCache.setCache('isRememberMe', isRememberMe.value)
}