每一個微信小程序均可以有本身的本地緩存,能夠經過 wx.setStorage(wx.setStorageSync)、wx.getStorage(wx.getStorageSync)、wx.clearStorage(wx.clearStorageSync)能夠對本地緩存進行設置、獲取和清理。本地緩存最大爲10MB。php
注意: localStorage 是永久存儲的,可是咱們不建議將關鍵信息所有存在 localStorage,以防用戶換設備的狀況。html
wx.setStorage(OBJECT)小程序
將數據存儲在本地緩存中指定的 key 中,會覆蓋掉原來該 key 對應的內容,這是一個異步接口。微信小程序
示例代碼微信
1
2
3
4
|
wx.setStorage({
key:
"key"
data:
"value"
})
|
wx.setStorageSync(KEY,DATA)異步
將 data 存儲在本地緩存中指定的 key 中,會覆蓋掉原來該 key 對應的內容,這是一個同步接口。學習
示例代碼.net
1
2
3
4
|
try
{
wx.setStorageSync(
'key'
,
'value'
)
}
catch
(e) {
}
|
wx.getStorage(OBJECT)
從本地緩存中異步獲取指定 key 對應的內容。
示例代碼:
1
2
3
4
5
6
|
wx.getStorage({
key:
'key'
,
success:
function
(res) {
console.log(res.data)
}
})
|
wx.getStorageSync(KEY)
從本地緩存中同步獲取指定 key 對應的內容。
示例代碼:
1
2
3
4
5
6
7
8
|
try
{
var
value = wx.getStorageSync(
'key'
)
if
(value) {
// Do something with return value
}
}
catch
(e) {
// Do something when catch error
}
|
wx.getStorageInfo(OBJECT)
異步獲取當前storage的相關信息
示例代碼:
1
2
3
4
5
6
7
|
wx.getStorageInfo({
success:
function
(res) {
console.log(res.keys)
console.log(res.currentSize)
console.log(res.limitSize)
}
})
|
wx.getStorageInfoSync
同步獲取當前storage的相關信息
示例代碼:
1
2
3
4
5
6
7
8
|
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 。
示例代碼:
1
2
3
4
5
6
|
wx.removeStorage({
key:
'key'
,
success:
function
(res) {
console.log(res.data)
}
})
|
wx.removeStorageSync(KEY)
從本地緩存中同步移除指定 key 。
示例代碼:
1
2
3
4
5
|
try
{
wx.removeStorageSync(
'key'
)
}
catch
(e) {
// Do something when catch error
}
|
wx.clearStorage()
清理本地數據緩存。
示例代碼:
1
|
wx.clearStorage()
|
wx.clearStorageSync()
同步清理本地數據緩存
示例代碼:
1
2
3
4
5
|
try
{
wx.clearStorageSync()
}
catch
(e) {
// Do something when catch error
}
|
以上就是本文的所有內容,但願對你們的學習有所幫助,也但願你們多多支持腳本之家。
原文連接:http://www.cnblogs.com/phpshen/p/6073176.html