2. Wechat applet data cache Storage

Using Wx. Getstorage and Wx. Setstorage in Api to realize a collection function. By reading the local data cache, judge whether the current article has been collected. If yes, the picture will be highlighted, otherwise it will be the opposite.

layout

<image wx:if="{{!isCollected}}" bindtap='handleCollection' src='/images/icon/collection-anti.png'></image>
<image wx:if="{{isCollected}}" bindtap='handleCollection' src='/images/icon/collection.png'></image>

Click image binding function

handleCollection(){
    //Reverse when clicking
    let isCollected = !this.data.isCollected;
    this.setData({
      isCollected
    })

    //Prompt users
    let title = isCollected ? 'Collection success':'Cancel collection';
    wx.showToast({
      title,
      icon:'success'
    })

    //Fetch data in cache
    wx.getStorage({
      key: 'isCollected',
      success:(res)=> {
        //Add current data to cache
        //let obj = {}; it cannot be emptied every time
        let obj = res.data;
        let {index} = this.data;
        obj[index] = isCollected;
        wx.setStorage({
          key: 'isCollected',
          data: obj,
          success:()=>{
            console.log('Cache success');
          }
        });
      },
    })
    
  }

When the page is loaded

data: {
    detailObj: {},
    isCollected: false,
    index: null
  },



  onLoad: function (options) {
    let index = options.index;
    this.setData({
      detailObj: datas.list_data[index],
      index
    });

    //Judge whether users collect current articles based on local cache data
    let detailStorage = wx.getStorageSync('isCollected');
    
    if(!detailStorage){
      wx.setStorageSync('isCollected', {})
    }
   
    //There are three values: true,false and undefined.
    if(detailStorage[index]){
      this.setData({
        isCollected:true
      })
    }
  },

Just post the code and add some comments. Let's talk about the difference between wx.getStorage() and wx.getStorageSync(). The former is asynchronous storage with callback function, the latter is synchronous without callback

Added by depsipher on Thu, 19 Dec 2019 22:00:29 +0200