一、cookie、localstorage、sessionstorage 三者的区别
1、存储大小:cookie4K、storage5M
2、有效期:cookie拥有有效期,storage永久存储
3、cookie会发送到服务器端,存储在内存中,storage只存储在浏览器端
4、路径:cookie有路径限制,storage住存储在域名下
5、API:cookie没有特定的API,storage有对应的API
二、为什么要封装storage
1、storage本身有API,但是只是简单的key/value形式
2、storage只存储字符串,需要手工转换成json对象
3、storage只能一次性清空,不能单个清空
// 封装sessionStorage
const STORAGE_KEY = 'mall'
export default {
// 设置值
setItem(key, value, module_name) {
if (module_name) {
let val = this.getItem(module_name)
if (val) {
val[key] = value
this.setItem(module_name, val)
}
} else {
let val = this.getStorage()
val[key] = value
window.sessionStorage.setItem(STORAGE_KEY, JSON.stringify(val))
}
},
// 获取某一个模块下面的属性user->username
getItem(key, module_name) {
if (module_name) {
let val = this.getStorage()[module_name]
if (val) return val[key]
}
return this.getStorage()[key]
},
// 获取所有storage对象
getStorage() {
return JSON.parse(window.sessionStorage.getItem(STORAGE_KEY) || '{}')
},
clear(key, module_name) {
let val = this.getStorage()
if (module_name) {
if (val[module_name]) {
delete val[module_name][key];
}
} else {
delete val[key]
}
window.sessionStorage.setItem(STORAGE_KEY, JSON.stringify(val))
}
}