微信小程序 緩存說明


每個微信小程序都可以有自己的本地緩存,可以通過 wx.setStorage(wx.setStorageSync)、wx.getStorage(wx.getStorageSync)、wx.clearStorage(wx.clearStorageSync)可以對本地緩存進行設置、獲取和清理。本地緩存最大為10MB。

注意: localStorage 是永久存儲的,但是我們不建議將關鍵信息全部存在 localStorage,以防用戶換設備的情況。

wx.setStorage(OBJECT)

將數據存儲在本地緩存中指定的 key 中,會覆蓋掉原來該 key 對應的內容,這是一個異步接口。

OBJECT參數說明:

示例代碼

?
1
2
3
4
wx.setStorage({
  key: "key"
  data: "value"
})

wx.setStorageSync(KEY,DATA)

將 data 存儲在本地緩存中指定的 key 中,會覆蓋掉原來該 key 對應的內容,這是一個同步接口。

OBJECT參數說明:

示例代碼

?
1
2
3
4
try {
   wx.setStorageSync( 'key' , 'value' )
} catch (e) { 
}

wx.getStorage(OBJECT)

從本地緩存中異步獲取指定 key 對應的內容。

OBJECT參數說明:

 示例代碼:

?
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的相關信息

OBJECT參數說明:

 success返回參數說明:

 示例代碼:

?
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 。

OBJECT參數說明:

示例代碼:

?
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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM