17 数据缓存

一,全局变量

(1)在app.js设置globalData的变量

App({
  onLaunch: function () {

    this.globalData.id = "51"
  },
  globalData: {
    id: null,
    name:null,
    passwd:null
  }
})

(2)在使用页面获得保存参数

1,获取应用实例;2,获得实例变量

const app = getApp()
Page({
  data: {
    id: null
  },
  onLoad: function () {
    var buffer=app.globalData.id;
    this.setData({
      id: buffer
    })
  }
})

二,setStorage

将数据存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容,这是一个异步接口。

参数类型必填说明
keyString本地缓存中的指定的 key
dataObject/String需要存储的内容
successFunction接口调用成功的回调函数
failFunction接口调用失败的回调函数
completeFunction接口调用结束的回调函数(调用成功、失败都会执行)

示例代码:

wx.setStorage({
  key:"key",
  data:"value"
})

三,getStorag

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

参数类型必填说明
keyString本地缓存中的指定的 key
successFunction接口调用的回调函数,res = {data: key对应的内容}
failFunction接口调用失败的回调函数
completeFunction接口调用结束的回调函数(调用成功、失败都会执行)

示例代码:

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

四,getStorageInfo

异步获取当前storage的相关信息

参数类型必填说明
successFunction接口调用的回调函数,详见返回参数说明
failFunction接口调用失败的回调函数
completeFunction接口调用结束的回调函数(调用成功、失败都会执行)

success返回参数说明:

参数类型说明
keysString Array当前storage中所有的key
currentSizeNumber当前占用的空间大小, 单位kb
limitSizeNumber限制的空间大小,单位kb

示例代码:

wx.getStorageInfo({
  success: function(res) {
    console.log(res.keys)
    console.log(res.currentSize)
    console.log(res.limitSize)
  }
})

五,removeStorage

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

参数类型必填说明
keyString本地缓存中的指定的 key
successFunction接口调用的回调函数
failFunction接口调用失败的回调函数
completeFunction接口调用结束的回调函数(调用成功、失败都会执行)

示例代码:

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

六,clearStorage()

清理本地数据缓存。

wx.clearStorage()

版权声明:本文为wzjisking原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。