### [微信小程序中数据缓存的解析](https://www.prosaas.cn/article/17339) **Published:** 2018-06-26T08:50:07 **Author:** 5201314 **Excerpt:** 这篇文章主要介绍了关于微信小程序中数据缓存的解析,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下… 这篇文章主要介绍了关于微信小程序中数据缓存的解析,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下 每个微信小程序都可以有自己的本地缓存,本篇文章主要介绍了微信小程序-详解数据缓存,可以通过函数可以对本地缓存进行设置、获取和清理,有兴趣的可以了解一下。 每个微信小程序都可以有自己的本地缓存,可以通过 wx.setStorage(wx.setStorageSync)、wx.getStorage(wx.getStorageSync)、wx.clearStorage(wx.clearStorageSync)可以对本地缓存进行设置、获取和清理。本地缓存最大为10MB。 注意: localStorage 是永久存储的,但是我们不建议将关键信息全部存在 localStorage,以防用户换设备的情况。 **wx.setStorage(OBJECT)** 将数据存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容,这是一个异步接口。 OBJECT参数说明:![](https://img.php.cn/upload/article/000/000/009/e39d6ded1cee4f41cc5c4b5593750348-0.png) 示例代码 wx.setStorage({ key:"key" data:"value" }) **wx.setStorageSync(KEY,DATA)** 将 data 存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容,这是一个同步接口。 OBJECT参数说明:![](https://img.php.cn/upload/article/000/000/009/e39d6ded1cee4f41cc5c4b5593750348-1.png) 示例代码 try { wx.setStorageSync('key', 'value') } catch (e) { } **wx.getStorage(OBJECT) ** 从本地缓存中异步获取指定 key 对应的内容。 OBJECT参数说明:![](https://img.php.cn/upload/article/000/000/009/e39d6ded1cee4f41cc5c4b5593750348-2.png) 示例代码: wx.getStorage({ key: 'key', success: function(res) { console.log(res.data) } }) **wx.getStorageSync(KEY)** 从本地缓存中同步获取指定 key 对应的内容。 参数说明:![](https://img.php.cn/upload/article/000/000/009/e39d6ded1cee4f41cc5c4b5593750348-3.png) 示例代码: 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参数说明:![](https://img.php.cn/upload/article/000/000/009/5d50103454e522d7ffcf9385be64c10a-4.png) success返回参数说明:![](https://img.php.cn/upload/article/000/000/009/5d50103454e522d7ffcf9385be64c10a-5.png) 示例代码: 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参数说明:![](https://img.php.cn/upload/article/000/000/009/5d50103454e522d7ffcf9385be64c10a-6.png) 示例代码: wx.removeStorage({ key: 'key', success: function(res) { console.log(res.data) } }) **wx.removeStorageSync(KEY)** 从本地缓存中同步移除指定 key 。 参数说明:![](https://img.php.cn/upload/article/000/000/009/5d50103454e522d7ffcf9385be64c10a-7.png) 示例代码: 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 } 以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网! 相关推荐: 微信小程序的自定义模态弹窗的介绍 微信小程序中显示html格式内容的方法 关于微信小程序Redux绑定的解析 以上就是微信小程序中数据缓存的解析的详细内容,更多请关注知企PROSAAS其它相关文章! **Categories:** 后端开发 ---