zoukankan      html  css  js  c++  java
  • vue缓存到localStorage

    构建模块

    // 存储每个商家是否收藏
    // id是商家id  
    // key是要存储的键favorite
    // value是存储的值布尔
    export function saveToLocal(id, key, value) {
      // 先把__seller__存储到h5缓存localStorage中
      let seller = window.localStorage.__seller__;
      // 如果seller是第一次存储
      if (!seller) {
        // 创建数据结构 seller = {id: {}}
        seller = {};
        seller[id] = {};
      } else {
        // 存储的JSON字符串转换为json对象
        seller = JSON.parse(seller);
        // 如果localStorage的__seller__中没有这个商家id
        if (!seller[id]) {
          // 就给它的值创建为对象
          seller[id] = {};
        }
      }
      // 最终把是否收藏的值存储到 localStorage中 商家id为123的key键中
      seller[id][key] = value;
      // 将JSON转换成为JSON字符串
      window.localStorage.__seller__ = JSON.stringify(seller);
      // 存储后的localStorage 就是 __seller__:"{"12345":{"favorite":true}}"
    };
    // 读取每个商家是否收藏
    // id是商家id  
    // key是要存储的键
    // def是当没有这个seller对象时返回def默认值
    export function loadFromLocal(id, key, def) {
      let seller = window.localStorage.__seller__;
      if (!seller) {
        return def;
      }
      // 读取之后要将JSON字符串转换成为JSON对象,同时拿到对应的id
      seller = JSON.parse(seller)[id];
      if (!seller) {
        return def;
      }
      let ret = seller[key];
      // 如果查询不到id就返回默认值
      return ret || def;
    };

    用的时候直接往里面传参

      methods: {
        toggleFavorite () {
          this.favorite = !this.favorite;
          // 使用
          saveToLocal(this.seller.id, 'favorite', this.favorite)
        },
      }
  • 相关阅读:
    蓝牙音箱的连接和断开
    画一个钟表,陪着我走
    利用MediaSession发送信息到蓝牙音箱
    修改Switch 的颜色
    ViewPager PagerAdapter 的使用
    错误:android.view.InflateException: Binary XML file line #167: Binary XML file line #167: Error inflating class <unknown>
    react-project(一)
    create-react-app重建
    nodeJS连接mysql
    nodeJS问题
  • 原文地址:https://www.cnblogs.com/gr07/p/9105532.html
Copyright © 2011-2022 走看看