封装localStorage和sessionStorage存储工具类
<script>
// 工具类
class Cache{
// 使用构造器,区分是 localStorage 还是 sessionStorage 存储
constructor(isLocal = true){
this.storage = isLocal ? localStorage : sessionStorage
}
setCache(key,value){
// localStorage 本身不能存储对象类型的数据,所以要使用 JSON.stringify() 将对象转成字符串
this.storage.setItem(key,JSON.stringify(value))
}
getCache(key){
const result = this.storage.getItem(key)
// 因为存储时已经将对象转为字符串了,所以在获取时要使用 JSON.parse() 转回对象类型
// 获取值时要将字符串类型的数据转为对象类型
// 因为如果是 undefined 会报错,所以在这里加一个判断更严谨
if(result){
return JSON.parse(result)
}
}
removerCache(key){
return this.storage.removeItem(key)
}
clear(){
this.storage.clear()
}
}
// Cache不传默认为 true ,就是 localStorage 存储
const localCache = new Cache()
// 使用工具类对象存储值
const userInfo = {
name:"why",
nickname:"coderwhy",
level:100,
imgURL:"www.baidu.com"
}
localCache.setCache("userInfo",userInfo)
console.log(localCache.getCache("userInfo"));
// Cache 传 false ,就是 sessionStorage 存储
const localCache2 = new Cache(false)
localCache2.setCache("sessionStorage","sdjfksdfsldl")
</script>