小程序---微信本地存储的方法使用

咱们在开发的过程当中,经常会用到本地存储,下面我给你们分享一下微信本地存储的使用。小程序

1、数据支持

须要存储的内容。只支持原生类型、Date、及可以经过JSON.stringify序列化的对象。缓存

2、方法

1、同步

(1wx.setStorageSync();  //存储值

 

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

 

(2wx.removeStorageSync();   // 移除指定的值

 

1 try {
2   wx.removeStorageSync('key')
3 } catch (e) {
4   // Do something when catch error
5 }

 

3wx.getStorageSync();  // 获取值

 

1 try {
2   var value = wx.getStorageSync('key')
3   if (value) {
4     // Do something with return value
5   }
6 } catch (e) {
7   // Do something when catch error
8 }

 

4wx.getStorageInfoSync();  // 获取当前 storage 中全部的 key

 

1 try {
2   const res = wx.getStorageInfoSync()
3   console.log(res.keys)
4   console.log(res.currentSize)
5   console.log(res.limitSize)
6 } catch (e) {
7   // Do something when catch error
8 }

 

5wx.clearStorageSync();  // 清除全部的key

 

1 try {
2   wx.clearStorageSync()
3 } catch(e) {
4   // Do something when catch error
5 }

 

2、异步

(1wx.setStorage();  //存储值

将数据存储在本地缓存中指定的 key 中。会覆盖掉原来该 key 对应的内容。数据存储生命周期跟小程序自己一致,即除用户主动删除或超过必定时间被自动清理,不然数据都一直可用。单个 key 容许存储的最大数据长度为 1MB,全部数据存储上限为 10MB微信

 

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

 

(2wx.removeStorage();   // 移除指定的值

 

1 wx.removeStorage({
2   key: 'key',
3   success (res) {
4     console.log(res)
5   }})

 

3wx.getStorage();  // 获取值

 

1 wx.getStorage({
2   key: 'key',
3   success (res) {
4     console.log(res.data)
5   }})

 

4wx.getStorageInfo();  // 获取当前 storage 中全部的 key

 

1 wx.getStorageInfo({
2   success (res) {
3     console.log(res.keys)
4     console.log(res.currentSize)
5     console.log(res.limitSize)
6   }})

 

5wx.clearStorage();  // 清除全部的key

 

1 wx.clearStorage()

 

  以上就是微信给咱们提供的本地存储的方法,但愿对你们有帮助!异步

相关文章
相关标签/搜索