这篇文章将为大家详细讲解有关怎么在微信小程序中缓存数据,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。
微信小程序可以通过wx.setStorage(wx.setStorageSync)、wx.getStorage(wx.getStorageSync)、wx.clearStorage(wx.clearStorageSync)对本地缓存进行设置、获取和清理。本地缓存最大为10MB。
wx.setStorage()———异步设置缓存
微信官方给出的属性
OBJECT参数说明:
参数 | 类型 | 必填 | 说明 |
---|---|---|---|
key | String | 是 | 本地缓存中的指定的 key |
data | Object/String | 是 | 需要存储的内容 |
success | Function | 否 | 接口调用成功的回调函数 |
fail | Function | 否 | 接口调用失败的回调函数 |
complete | Function | 否 | 接口调用结束的回调函数(调用成功、失败都会执行) |
调用方式:
wx.setStorage({ key:"key", data:"value" })
wx.setStorageSync()———同步设置缓存
微信官方给出的属性
参数说明:
参数 | 类型 | 必填 | 说明 |
---|---|---|---|
key | String | 是 | 本地缓存中的指定的 key |
data | Object/String | 是 | 需要存储的内容 |
调用方式:
try { wx.setStorageSync('key', 'value') } catch (e) { }
wx.getStorage()——–异步获取缓存
微信官方给出的属性
OBJECT参数说明:
参数 | 类型 | 必填 | 说明 |
---|---|---|---|
key | String | 是 | 本地缓存中的指定的 key |
success | Function | 是 | 接口调用的回调函数,res = {data: key对应的内容} |
fail | Function | 否 | 接口调用失败的回调函数 |
complete | Function | 否 | 接口调用结束的回调函数(调用成功、失败都会执行) |
success返回参数说明:
参数 | 类型 | 说明 |
---|---|---|
data | String | key对应的内容 |
调用方式:
wx.getStorage({ key: 'key', success: function(res) { console.log(res.data) } })
wx.getStorageSync()——–同步获取缓存数据
微信官方给出的属性说明
参数说明:
参数 | 类型 | 必填 | 说明 |
---|---|---|---|
key | String | 是 | 本地缓存中的指定的 key |
调用方式:
try { var value = wx.getStorageSync('key') if (value) { // Do something with return value } } catch (e) { // Do something when catch error }
wx.getStorageInfo()——异步获取当前缓存的数据
微信官方给出的属性说明
OBJECT参数说明:
参数 | 类型 | 必填 | 说明 |
---|---|---|---|
success | Function | 是 | 接口调用的回调函数,详见返回参数说明 |
fail | Function | 否 | 接口调用失败的回调函数 |
complete | Function | 否 | 接口调用结束的回调函数(调用成功、失败都会执行) |
success返回参数说明:
参数 | 类型 | 说明 |
---|---|---|
keys | String Array | 当前storage中所有的key |
currentSize | Number | 当前占用的空间大小, 单位kb |
limitSize | Number | 限制的空间大小,单位kb |
调用方式:
wx.getStorageInfo({ success: function(res) { console.log(res.keys) console.log(res.currentSize) console.log(res.limitSize) } })
wx.getStorageInfoSync()——-同步获取当前缓存数据
emmmmm—微信并没有给参数说明
调用方式:
try { var res = wx.getStorageInfoSync() console.log(res.keys) console.log(res.currentSize) console.log(res.limitSize) } catch (e) { // Do something when catch error }
wx.removeStorage()—–异步移除指定的key的缓存数据
微信官方参数说明
OBJECT参数说明:
参数 | 类型 | 必填 | 说明 |
---|---|---|---|
key | String | 是 | 本地缓存中的指定的 key |
success | Function | 是 | 接口调用的回调函数 |
fail | Function | 否 | 接口调用失败的回调函数 |
complete | Function | 否 | 接口调用结束的回调函数(调用成功、失败都会执行) |
调用方式:
wx.removeStorage({ key: 'key', success: function(res) { console.log(res.data) } })
wx.removeStorageSync()——同步移除指定key的缓存数据
微信官方参数说明
参数说明:
参数 | 类型 | 必填 | 说明 |
---|---|---|---|
key | String | 是 | 本地缓存中的指定的 key |
调用方式:
try { wx.removeStorageSync('key') } catch (e) { // Do something when catch error }
wx.clearStorage()——异步清理本地缓存
调用方式:
wx.clearStorage()
wx.clearStorageSync()——-同步清理本地缓存
调用方式:
try { wx.clearStorageSync() } catch(e) { // Do something when catch error }