每个微信小程序都可以有自己的本地缓存,可以通过 wx.setStorage
/wx.setStorageSync
、wx.getStorage
/wx.getStorageSync
、wx.clearStorage
/wx.clearStorageSync
,wx.removeStorage
/wx.removeStorageSync
对本地缓存进行读写和清理。
上面的set和get都有对应的Sync方法,带Sync的方法为同步方法、不带Sync的方法为异步方法。
缓存可以保存数组、数值、字符串、对象。
将数据存储在本地缓存中指定的 key 中。会覆盖掉原来该 key 对应的内容。除非用户主动删除或因存储空间原因被系统清理,否则数据都一直可用
。单个 key 允许存储的最大数据长度为 1MB,所有数据存储上限为 10MB。
提供setStorage和setStorageSync两个接口.
// 异步设置
wx.setStorage({
key:"key",
data:"value"
})
// 同步设置
wx.setStorageSync('key', 'value')
// 异步获取
wx.getStorage({
key: 'key',
success (res) { // 从 success 回调中获取返回的数据
console.log(res.data)
}
})
// 同步获取
var value = wx.getStorageSync('key')
// 异步移除
wx.removeStorage({
key: 'key',
success (res) {
console.log(res)
}
})
// 同步移除
try {
wx.removeStorageSync('key')
} catch (e) {
// Do something when catch error
}
// 异步清理
wx.clearStorage()
// 同步清理
wx.clearStorageSync()
同一个微信用户,同一个小程序 storage 上限为 10MB。storage 以用户维度隔离,同一台设备上,A 用户无法读取到 B 用户的数据;不同小程序之间也无法互相读写数据。
同一小程序使用不同插件:不同插件之间,插件与小程序之间 storage 不互通。
不同小程序使用同一插件:同一插件 storage 不互通。
1、本地缓存的清理时机跟代码包一样,只有在代码包被清理的时候本地缓存才会被清理。
2、储存空间不足,会清空最近最久未使用的小程序的本地缓存。
3、移除小程序数据消失
4、localstorage,无时效性,除非手动清理,不然一直都在。
对于数据需求较小的历史记录、购物车、用户登录信息、小程序自定义设置等都可以使用 storage 进行缓存
[1]
参考文档: https://developers.weixin.qq.com/miniprogram/dev/api/storage/wx.setStorage.html[2]
更多使用方法: https://developers.weixin.qq.com/miniprogram/dev/api/storage/wx.getStorage.html[3]
参考文档: https://developers.weixin.qq.com/miniprogram/dev/api/storage/wx.removeStorage.html[4]
参考文档: https://developers.weixin.qq.com/miniprogram/dev/api/storage/wx.clearStorage.html