Storage
localStorage
永久性的存储方法
- 属性
- length
- 方法
Storage.key(index)
: 返回存储中的第n个key名称Storage.getItem(key)
Storage.setItem(key,value)
Storage.removeItem(key)
Storage.clear()
sessionStorage
临时存储方法,会话关闭,存储内容会被清除
getItem(key)
setItem(key,value)
Storage封装
class Cache {
constructor(isLocal = true){
this.storage = isLocal?localStorage:sessionStorage
}
setCache(key,value){
if (!value) {
throw new Error('value error: value 必须有值')
}
this.storage.setItem(key,JSON.stringify(value))
}
getCache(key){
const result = this.storage.getItem(key)
if(result){
return JSON.parse(result)
}
}
removeCache(key){
this.storage.removeItem(key,value)
}
clear(key,value){
this.storage.clear()
}
}
const localCache = new Cache()
const sessionCache = new Cache(false)