为什么要封装Storage?
- Storage本身有API,但只是简单的key / value 形式
- Storage只存储字符串,需要手动转化成json对象
- Storage只能一次性清空,不能单个清空
//数据存储
/**
* Storage封装
*/
const STORGE_KEY = 'mall'; // 定义一个key
export default {
//存储值
setItem(key, value, module_name) {
if (module_name) {
let val = this.getItem(module_name);
val[key] = value;
this.setItem(module_name, val);
} else {
let val = this.getStorage();
val[key] = value;
window.sessionStorage.setItem(STORGE_KEY, JSON.stringify(val));
}
},
//获取某一个模块下面的user下面的userName
getItem(key, module_name) {
if (module_name) {
let val = this.getItem(module_name);
if (val) return val[key];
}
return this.getStorage()[key];
},
// 获取整个数据
getStorage() {
return JSON.parse(window.sessionStorage.getItem(STORGE_KEY) || '{}');
},
//清空某一个值
clear(key, module_name) {
let val = this.getStorage();
if (module_name) {
delete val[module_name][key];
} else {
delete val[key];
}
window.sessionStorage.setItem(STORAGE_KEY, JSON.stringify(val));
},
};