vue项目中localstorage的封装

56 阅读1分钟
// 封装的方法,尽量和原生方法相似,减少学习和记忆成本
import config from "../config";
export default {
  // 设置
  setItem(key, value) {
    // 定义存储的key和value
    // 存储的key,是当前命名空间的名字
    const storageKey = config.nameSpace;
    // 存储的value,就是接收的两个形参
    let storageValue = { [key]: value };
    // 先取出原来的storage对应的value,如果没有,返回空对象类型字符串
    let oldStorageValue = window.localStorage.getItem(storageKey) || "{}";
    // 取出来的是json字符串,需要转成对象
    oldStorageValue = JSON.parse(oldStorageValue);
    //原来的数据和新的数据要合并
    storageValue = { ...oldStorageValue, ...storageValue };
    // 把合并好的数据,转成json字符串
    storageValue = JSON.stringify(storageValue);
    // 把相关的key和value写到localstorage里面
    window.localStorage.setItem(storageKey, storageValue);
  },
  // 获取
  getItem(key) {
    // 通过命名空间,找到存储的value对象,现在是一个json格式字符串
    let storageValue = window.localStorage.getItem(config.nameSpace) || "{}";
    // 字符串转对象
    storageValue = Json.parse(storageValue);
    // 通过key,从对象中取值并返回
    return storageValue[key];
  },
  // 清除某一项
  clearItem(key) {
    // 通过命名空间,找到存储的value,存储的格式的json字符串
    let storageValue = window.localStorage.getItem(config.nameSpace) || "{}";
    // 字符串转对象
    storageValue = JSON.parse(storageValue);
    // 从对象中删除指定的key
    delete storageValue[key];
    // 删完之后,写回去
    // 转字符串
    storageValue = JSON.stringify(storageValue);
    // 使用原生的api,写回去
    window.localStorage.setItem(config.nameSpace, storageValue);
  },
  // 清除所有
  clearAll() {
    // 调用原生api即可
    window.localStorage.clear();
  },
};