每个微信小程序都可以有自己的本地缓存,本篇文章主要介绍了微信小程序-详解数据缓存,可以通过函数可以对本地缓存进行设置、获取和清理,有兴趣的可以了解一下。
每个微信小程序都可以有自己的本地缓存,可以通过 wx.setstorage(wx.setstoragesync)、wx.getstorage(wx.getstoragesync)、wx.clearstorage(wx.clearstoragesync)可以对本地缓存进行设置、获取和清理。本地缓存最大为10mb。
注意: localstorage 是永久存储的,但是我们不建议将关键信息全部存在 localstorage,以防用户换设备的情况。
wx.setstorage(object)
将数据存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容,这是一个异步接口。
object参数说明:
示例代码
wx.setstorage({
key:"key"
data:"value"
})
wx.setstoragesync(key,data)
将 data 存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容,这是一个同步接口。
object参数说明:
示例代码
try {
wx.setstoragesync('key', 'value')
} catch (e) {
}
wx.getstorage(object)
从本地缓存中异步获取指定 key 对应的内容。
object参数说明:
示例代码:
wx.getstorage({
key: 'key',
success: function(res) {
console.log(res.data)
}
})
wx.getstoragesync(key)
从本地缓存中同步获取指定 key 对应的内容。
参数说明:
示例代码:
try {
var value = wx.getstoragesync('key')
if (value) {
// do something with return value
}
} catch (e) {
// do something when catch error
}
wx.getstorageinfo(object)
异步获取当前storage的相关信息
object参数说明:
success返回参数说明:
示例代码:
wx.getstorageinfo({
success: function(res) {
console.log(res.keys)
console.log(res.currentsize)
console.log(res.limitsize)
}
})
wx.getstorageinfosync
同步获取当前storage的相关信息
示例代码:
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(object)
从本地缓存中异步移除指定 key 。
object参数说明:
示例代码:
wx.removestorage({
key: 'key',
success: function(res) {
console.log(res.data)
}
})
wx.removestoragesync(key)
从本地缓存中同步移除指定 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
}
以上就是图文详解微信小程序数据缓存的详细内容。