localStorage:本地存储,提供的是一种永久性存储方法,在浏览器重新打开时,存储的内容依然保留
sessionStorage:会话存储,提供得是本次会话得存储,在关闭会话时,存储得内容被删除
存放数据大小:
localStorage和sessionStorage:可以保存5MB的信息。
方法:因为localStorage和sessionStorage都是一样的方法,我就简写了
- 设置Storage setItem(name,value)
- 获取值 getItem(name)
- 删除指定键名数据 removeItem(name)
- 清空所有数据 clear()
- key(索引)
属性:
- length()
在vue的项目中封装成工具函数来使用
class Cache {
//默认使用localStorage
constructor(isLocal = true) {
this.storage = isLocal ? localStorage : sessionStorage
}
setItem(key, value) {
if (value) {
this.storage.setItem(key, JSON.stringify(value))
}
}
getItem(key) {
let value = this.getItem(key)
if (value) {
value = JSON.parse(value)
return value
}
}
removeItem(key) {
this.storage.removeItem(key)
}
clear() {
this.storage.clear()
}
length() {
return this.storage.length
}
key(index) {
return this.storage.key(index)
}
}
const localStorage = new caches()
const sessionStorage = new caches(false)
export { localStorage, sessionStorage }