微信小程序数据缓存

微信小程序提供了wx.setStorage、wx.getStorage、wx.clearStorage等方法来管理本地缓存,本地存储最大为10MB。建议避免将关键信息全存于localStorage,因为换设备可能导致数据丢失。这些API包括同步和异步版本,可用于设置、获取和清理本地数据。
摘要由CSDN通过智能技术生成

每个微信小程序都可以有自己的本地缓存,可以通过 wx.setStorage(wx.setStorageSync)、wx.getStorage(wx.getStorageSync)、wx.clearStorage(wx.clearStorageSync)可以对本地缓存进行设置、获取和清理。本地缓存最大为10MB。

注意: localStorage 是永久存储的,但是我们不建议将关键信息全部存在 localStorage,以防用户换设备的情况。

wx.setStorage(OBJECT)

将数据存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容,这是一个异步接口。

OBJECT参数说明:
在这里插入图片描述
示例代码

wx.setStorage({
 key:"key"
 data:"value"
})

wx.setStorageSync(KEY,DATA)

将 data 存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容,这是一个同步接口。

OBJECT参数说明:
在这里插入图片描述
示例代码

try {
  wx.setStorageSync('key', 'value')
} catch (e) {  
}

wx.getStorage(OBJECT)

从本地缓存中异步获取指定 key 对应的内容。

OBJECT参数说明:
在这里插入图片描述
示例代码:

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参数说明:

在这里插入图片描述

success返回参数说明:
在这里插入图片描述
示例代码:

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
}

原文链接:https://www.xuebuyuan.com/3291812.html
原文链接:https://www.yisu.com/zixun/353725.html

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值