微信小程序 緩存
關于本地緩存
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" 設置本地存儲
新聞熱點
疑難解答