Web Storage
- webStorage 提供了一种机制,可以让浏览器提供一种比cookie更加直观的key value存储方式
- local storage: 本地存储,是一种永久性的存储方法,在关闭网页重新打开的时候,存储的内容依然存在
- sessionStorage: 会话存储,提供的是本次会话的存储,在关闭会话的时候,存储的内容依然会被清除
Local Storage
- 持久化存储 除非自动删除,否则会一直存在
- 作用域,同域名,不同标签,不同窗口
- 获取方式: window.localStorage
- API
- localStorage.setItem()
- 存储的值可以是字符串,数字,布尔值,数组对象,数组和对象必须转换成为string进行存储,通过JSON.parse() 和JSON.stringify()搭配使用
- localStorage.getItem()
- 如果key对应的值获取不到,则返回的值是null
- localStorage.removeItem(key)
- localStorage.clear()
- 在不确定是否存在key的情况下,可以使用hasOwnProperty()进行检查,返回true 或者false
- 可以使用Object.keys()查看所有存储数据的键
sessionStorage
- 会话级别,浏览器标签页或者窗口关闭
- 作用域,同域名,同源窗口
- 获取方式: window.sessionStorage
- API
- sessionStorage.setItem()
- 存储的值可以是字符串,数字,布尔值,数组对象,数组和对象必须转换成为string进行存储,通过JSON.parse() 和JSON.stringify()搭配使用
- sessionStorage.getItem()
- 如果key对应的值获取不到,则返回的值是null
- sessionStorage.removeItem(key)
- sessionStorage.clear()
- 在不确定是否存在key的情况下,可以使用hasOwnProperty()进行检查,返回true 或者false
- 可以使用Object.keys()查看所有存储数据的键
封装
class Cache {
constructor(isLocal = true) {
this.storage = isLocal ? localStorage: sessionStorage
}
setCache(key ,value) {
if(!value) {
throw new Error("value error: value必须有值")
}
if (value){
this.storage.setItem(key,JSON.stringify(value))
}
}
getCache(e) {
const result = this.storage.getItem(key)
if (result) {
return JSON.parse(result)
}
}
removeCache(key) {
this.storage.removeItem(key)
}
clear() {
this.storage.clear()
}
}