微信小程序 缓存
关于本地缓存
1.wx.setStorage(wx.setStorageSync)、wx.getStorage(wx.getStorageSync)、wx.clearStorage(wx.clearStorageSync)
可以对本地缓存进行设置、获取和清理。本地缓存最大为10MB
2.localStorage 是永久存储
一、异步缓存
wx.setStorage(OBJECT)
将数据存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容
wx.setStorage({ key:"key", data:"value"}) wx.getStorage(OBJECT)
从本地缓存中异步获取指定 key 对应的内容。
wx.getStorage({ key: 'key', success: function(res) { console.log(res.data) }})wx.getStorageInfo(OBJECT)
异步获取当前storage的相关信息
wx.getStorageInfo({ success: function(res) { console.log(res.keys) console.log(res.currentSize) console.log(res.limitSize) }})wx.removeStorage(OBJECT)
从本地缓存中异步移除指定 key 。
wx.removeStorage({ key: 'key', success: function(res) { console.log(res.data) }})二、同步缓存
wx.setStorageSync(KEY,DATA)
将 data 存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容,这是一个同步接口。
wx.getStorageSync(KEY)
从本地缓存中同步获取指定 key 对应的内容。
wx.getStorageInfoSync
同步获取当前storage的相关信息
wx.removeStorageSync(KEY)
从本地缓存中同步移除指定 key 。
三、清理缓存
wx.clearStorage()
清理本地数据缓存。
wx.clearStorageSync()
同步清理本地数据缓存
关于同步缓存和异步缓存的区别
以Sync(同步,同时)结尾的都是都是同步缓存,二者的区别是,异步不会阻塞当前任务,同步缓存直到同步方法处理完才能继续往下执行。
但是一般情况下不要用清除所有的缓存,如果想要清除相应的缓存,设置对应的缓存内容为空数组就好
关于历史搜索
<input type="text" class="search-icon" placeholder="请输入要搜索的内容" bindinput="searchNameInput"/><text bindtap="setSearchStorage">搜索</text><view> <view> <text style="float:left;" bindtap="deleteHistory">历史搜索</text> <text style="float:right;" bindtap="deleteHistory">删除搜索历史</text> </view> <view> <view class="search-list" wx:for="{{searchData}}" wx:key="item"> <view>{{item == null?'暂无数据':item}}</view> </view> </view></view>页面
这里有三个绑定事件
bindinput="searchNameInput" 获取用户输入的数据
bindtap="setSearchStorage" 设置本地存储
新闻热点
疑难解答