本地資料緩存常用于存儲多頁面用到的資料,例如使用者頭像資訊、
(1)資料存儲
wx.setStorage(Object object)與wx.setStorageSync(string key, any data)
wx.setStorage({
key:"key",
data:"value"
})
同步文法:
try {
wx.setStorageSync('key', 'value')
} catch (e) {
...
}
日常開發裡為了資料的正确執行擷取,一般使用wx.setStorageSync,即wx.setStorage 的同步版本,進行資料存儲。詳情參見微信小程式---存儲本地緩存資料
【拓展】關于同步緩存和異步緩存的差別
以Sync(同步,同時)結尾的都是都是同步緩存,二者的差別是,異步不會阻塞目前任務,同步緩存直到同步方法處理完才能繼續往下執行。
通俗點說,異步就是不管保沒儲存成功,程式都會繼續往下執行.同步是等儲存成功了,才會執行下面的代碼.
使用異步,性能會更好;而使用同步,資料會更安全。
Synchronize同步
(2)擷取指定 key 的内容
wx.getStorage(Object object)與wx.getStorageSync(string key)
wx.getStorage({
key: 'key',
success (res) {
console.log(res.data)
}
})
同步文法:
try {
var value = wx.getStorageSync('key')
if (value) {
// Do something with return value
}
} catch (e) {
// Do something when catch error
}
其他頁面擷取資料
<view class="showUserArea">
<image src="{{userInfo.avatarUrl}}"></image>
<text>{{userInfo.nickName}}</text>
</view>
/* 使用者展示區域 */
.showUserArea{
width: 100%;
height: 400rpx;
background:#388bff;
display: flex;
flex-direction: column;
align-items:center;/*垂直居中*/
justify-content: center;/*水準居中*/
}
.showUserArea>image{
width: 128rpx;
height: 128rpx;
border-radius: 50%;
}
onShow(){
var res = wx.getStorageSync('userInfo');//擷取緩存使用者資料
try {
if (res) {
this.setData({
userInfo: res
})
}
} catch (e) {
// Do something when catch error
}
}
遺留問題:真機測試擷取失敗。。。。。。。。。
(3)擷取目前storage的相關資訊
wx.getStorageInfo(Object object)與Object wx.getStorageInfoSync()
wx.getStorageInfo({
success (res) {
console.log(res.keys)
console.log(res.currentSize)
console.log(res.limitSize)
}
})
同步版本:
try {
const res = wx.getStorageInfoSync()
console.log(res.keys)
console.log(res.currentSize)
console.log(res.limitSize)
} catch (e) {
// Do something when catch error
}
(4)本地緩存中移除指定 key
wx.removeStorage(Object object)與wx.getStorageSync(string key)
wx.getStorage({
key: 'key',
success (res) {
console.log(res.data)
}
})
同步版本:
try {
var value = wx.getStorageSync('key')
if (value) {
// Do something with return value
}
} catch (e) {
// Do something when catch error
}
(5)清理本地資料緩存
wx.clearStorage(Object object)與wx.clearStorageSync()
wx.clearStorage()
同步版本:
try {
wx.clearStorageSync()
} catch(e) {
// Do something when catch error
}