本地数据缓存
异步存储方法:
- 异步存: wx.setStorage
- 异步取: wx.getStorage
- 异步清理: wx.clearStorage
同步存储方法
- 同步存:wx.setStorageSync
- 同步取: wx.getStorageSync
- 同步清理: wx.clearStorageSync
注意
同一个小程序 storage 上限为 10MB。
localStorage 以用户维度隔离,同一台设备上,A 用户无法读取到 B 用户的数据。
异步存储方法:
存数据
wx.setStorage(object) 相同key会覆盖,可写回调方法
获取方法:
wx.getStorage(object)
清除方法:
wx.clearStorage()里面可以写回调函数 成功,失败,完成
<!--动态获取数据-->
<text>{{storageContent}}</text>
<!--存-->
<button type="primary" bindtap="listenerStorageSave">storage存储信息会在text上显示</button>
<!--取-->
<button type="primary" bindtap="listenerStorageGet">获取storage存储的信息</button>
<!--清-->
<button type="warn" bindtap="listenerStorageClear">清楚异步存储数据</button>
Page({
data: {
storageContent: '',
},
onLoad: function (options) {
// 页面初始化 options为页面跳转所带来的参数
},
/**
* 异步存储
*/
listenerStorageSave: function () {
//以键值对的形式存储 传进去的是个对象
wx.setStorage({
key: 'key',
data: '我是storeage异步存储的信息',
success: function (res) {
console.log(res)
}
})
},
/**
* 异步获取信息
*/
listenerStorageGet: function () {
var that = this;
wx.getStorage({
//获取数据的key
key: 'key',
success: function (res) {
console.log(res)
that.setData({
//
storageContent: res.data
})
},
/**
* 失败会调用
*/
fail: function (res) {
console.log(res)
}
})
},
/**
* 异步清除数据
*/
listenerStorageClear: function () {
var that = this;
wx.clearStorage({
success: function (res) {
that.setData({
storageContent: ''
})
}
})
}
})
同步存储方法:
存数据 相同key会覆盖
wx.setStorageSync(key,data)
读数据
wx.getStorageSync(key) 存储是指定的key
清除数据
wx.clearStorageSync() 不可写回调方法
<text>{{storageSyncContent}}</text>
<button type="primary" bindtap="listenerStorageSyncSave">storageSync存储信息会在text上显示</button>
<button type="primary" bindtap="listenerStorageSyncGet">获取storageSync存储信息</button>
<button type="warn" bindtap="listenerStorageSyncClear">清除同步存储数据</button>
Page({
data: {
storageSyncContent: ''
},
onLoad: function (options) {
// 页面初始化 options为页面跳转所带来的参数
},
/**
* 数据同步存储
*/
listenerStorageSyncSave: function () {
wx.setStorageSync('key', '我是同步存储的数据')
},
/**
* 数据同步获取
*/
listenerStorageSyncGet: function () {
// var that = this;
var value = wx.getStorageSync('key')
this.setData({
storageSyncContent: value
})
},
/**
* 清除同步存储数据
*/
listenerStorageSyncClear: function () {
wx.clearStorageSync()
}
})