关于本地缓存
1.wx.setStorage(wx.setStorageSync)、wx.getStorage(wx.getStorageSync)、wx.clearStorage(wx.clearStorageSync)可以对本地缓存进行设置、获取和清理。本地缓存最大为10MB
2.localStorage 是永久存储
相应的api----------
wx.setStorage(OBJECT)
wx.getStorage(OBJECT)
wx.getStorageInfo(OBJECT)
wx.removeStorage(OBJECT)
wx.setStorageSync(KEY,DATA)
wx.getStorageSync(KEY)
wx.getStorageInfoSync
wx.clearStorage()
wx.clearStorageSync() ...
Api的具体使用详见官方文档
注意:这里又一个问题就是这些缓存不清理会永久的缓存----------然而实际开发中,我们往往需要设置一些缓存的时效性
所以就需要对这些api进行封装(二次开发)直接上代码
设置缓存-----------put(key, val, time) time为可选参数表示有效时间(单位:秒)
function put(key, val, time) {wx.setStorageSync(key, val)var seconds = parseInt(time);if (seconds > 0) {var timestamp = Date.parse(new Date());timestamp = timestamp / 1000 + seconds;wx.setStorageSync(k + 'dtime', timestamp + "")} else {wx.removeStorageSync(k + 'dtime')}}
读取缓存-----get(key, def)-------def为可选参数,表示无缓存数据时返回值(支持字符串、json、数组、boolean等等)
function get(key, def) {var deadtime = parseInt(wx.getStorageSync(key+ 'dtime'))if (deadtime) {if (parseInt(deadtime) < Date.parse(new Date()) /1000) {if (def) { return def; }else { return; }}}var res = wx.getStorageSync(key);if (res) {return res;} else {return def;}}
以上所述是小编给大家介绍的微信小程序缓存时效性详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对错新站长站网站的支持!
新闻热点
疑难解答