🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# 存储数据和读取数据 ### wx.setStorage(OBJECT) 将数据存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容,这是一个异步接口。 **OBJECT参数说明:** | 参数 | 类型 | 必填 | 说明 | | -------- | ------------- | ---- | ------------------------ | | key | String | 是 | 本地缓存中的指定的 key | | data | Object/String | 是 | 需要存储的内容 | | success | Function | 否 | 接口调用成功的回调函数 | | fail | Function | 否 | 接口调用失败的回调函数 | | complete | Function | 否 | 接口调用结束的回调函数(调用成功、失败都会执行) | ### wx.getStorage(OBJECT) 从本地缓存中异步获取指定 key 对应的内容。 **OBJECT参数说明:** | 参数 | 类型 | 必填 | 说明 | | -------- | -------- | ---- | -------------------------------- | | key | String | 是 | 本地缓存中的指定的 key | | success | Function | 是 | 接口调用的回调函数,res = {data: key对应的内容} | | fail | Function | 否 | 接口调用失败的回调函数 | | complete | Function | 否 | 接口调用结束的回调函数(调用成功、失败都会执行) | **success返回参数说明:** | 参数 | 类型 | 说明 | | ---- | ------ | -------- | | data | String | key对应的内容 | ### 示例 在A页面调用 setStorage 存储一些数据: ```html <button bindtap="setDatas">设置数据</button> ``` ```js const utils = require('../../libs/utils') Page({ setDatas () { wx.setStorage({ key: 'transactionData', data: { name: 'qzy', age: 22 }, success: function(res){ console.log('存储成功') console.log(res) }, fail: function() { console.log('存储失败') }, complete: function() { console.log('存储完毕') } }) } }) ``` 在B页面调用 getStorage 获取刚才存储的数据: ```html <button bindtap="getDatas">获取数据</button> ``` ```js Page({ getDatas () { wx.getStorage({ key: 'transactionData', success: function(res){ console.log('获取成功') console.log(res) }, fail: function() { console.log('获取失败') }, complete: function() { console.log('获取完毕') } }) } }) ``` :-: ![](http://xiaoyulive.oss-cn-beijing.aliyuncs.com/imgs/weixin/024.png) ## 同步调用接口 小程序支持同步存储和读取数据缓存,用法与异步。 ### wx.setStorageSync(KEY,DATA) 将 data 存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容,这是一个同步接口。 **参数说明:** | 参数 | 类型 | 必填 | 说明 | | ---- | ------------- | ---- | ------------- | | key | String | 是 | 本地缓存中的指定的 key | | data | Object/String | 是 | 需要存储的内容 | **示例代码** ```js try { wx.setStorageSync('key', 'value') } catch (e) { } ``` ### wx.getStorage(OBJECT) 从本地缓存中异步获取指定 key 对应的内容。 **OBJECT参数说明:** | 参数 | 类型 | 必填 | 说明 | | -------- | -------- | ---- | -------------------------------- | | key | String | 是 | 本地缓存中的指定的 key | | success | Function | 是 | 接口调用的回调函数,res = {data: key对应的内容} | | fail | Function | 否 | 接口调用失败的回调函数 | | complete | Function | 否 | 接口调用结束的回调函数(调用成功、失败都会执行) | **success返回参数说明:** | 参数 | 类型 | 说明 | | ---- | ------ | -------- | | data | String | key对应的内容 | **示例代码** ```js try { var value = wx.getStorageSync('key') if (value) { // Do something with return value } } catch (e) { // Do something when catch error } ```