微信小程序之數據緩存實例-備忘錄
數據緩存在移動端的使用是非常重要的,既可以減少用戶的流量支出又可以提高程序的訪問速度和用戶體驗。每個微信小程序都可以有自己的本地緩存,可以通過 wx.setStorage(wx.setStorageSync)、wx.getStorage(wx.getStorageSync)、wx.clearStorage(wx.clearStorageSync)可以對本地緩存進行設置、獲取和清理。同一個微信用戶,同一個小程序 storage 上限為 10MB。
一、 Wx.setStorage(OBJECT)
將數據存儲在本地緩存中指定的 key 中,會覆蓋掉原來該 key 對應的內容,這是一個異步接口。
object參數說明:
示例代碼:
wx.setStorage({ key:"key", data:"value" })
- wx.setStorageSync(KEY,DATA)
將 data 存儲在本地緩存中指定的 key 中,會覆蓋掉原來該 key 對應的內容,這是一個同步接口。
參數說明:
示例代碼:
try { wx.setStorageSync('key', 'value') } catch (e) { }
- wx.getStorage(OBJECT)
從本地緩存中異步獲取指定 key 對應的內容。
OBJECT參數說明:
success返回參數說明:
示例代碼:
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參數說明:
示例代碼:
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 }
項目效果: