微信小程序 数据缓存

数据本地存储

官方文档 wx.getStorage......

wx.setStorageSync和wx.setStorage   以Sync结尾的是同步的方法,其它的是异步的方法  举几个异步的方法为例

wx.setStorage

将数据存储在本地缓存中指定的 key 中。会覆盖掉原来该 key 对应的内容。除非用户主动删除或因存储空间原因被系统清理,否则数据都一直可用。单个 key 允许存储的最大数据长度为 1MB,所有数据存储上限为 10MB。

  onLoad: function (options) {
    wx.setStorage({
      key: 'name',
      data: '张三'
    })
    wx.setStorage({
      key: 'age',
      data: '20'
    })
  },

获取存储的本地数据

<button class="btn" bindtap="getStorage">获取数据name</button>
<button class="btn" bindtap="removeStorage">移除数据name</button>
<button class="btn" bindtap="clearStorage">清除全部数据</button>
<button class="btn" bindtap="getAge">获取数据age</button>

wx.getStorage

从本地缓存中异步获取指定 key 的内容

 getStorage:function(){
    wx.getStorage({
      key: 'name',
      success:function(res){
        console.log(res.data)
      }
    })
  },
 getAge:function(){
    wx.getStorage({
      key: 'age',
      success:function(res){
        console.log(res.data)
      }
    })
  },

wx.removeStorage

从本地缓存中移除指定 key。

removeStorage:function(){
    wx.removeStorage({
      key: 'name',
      success:function(res){
        console.log(res)
      }
    })
  },

wx.clearStorage

clearStorage:function(){
    wx.clearStorage({
      success: (res) => {
        console.log(res)
      }
    })
  },

数据存储结合项目

  • 先判断本地存储中是否有存储好的数据

  • 没有存储好的数据 就发送请求 有存储好的数据就直接使用本地数据

  onLoad: function (options) {
    // 判断本地是否存储了 当前数据
    var as = wx.getStorageSync('arrs')
    if(!as){ 
      //如果本地没存储   发送AJAX请求
      console.log(11111)
      wx.request({
        url: 'http://106.75.79.117:3000/aslide',
        success:(res) => {
          console.log(res.data)
          var arrs = res.data
          wx.setStorageSync('arrs', arrs)
          this.setData({
            aslideLeftTit:arrs,
            children:arrs[0].children,
            title:arrs[0].name
          })
        }
      })
    }else{
      console.log(2222)
      this.setData({
        aslideLeftTit:as,
        children:as[0].children,
        title:as[0].name
      })
    }
  },

猜你喜欢

转载自blog.csdn.net/weixin_41040445/article/details/114695578