app.js - 启动时 onLaunch 拉取本地缓存的日志记录
const logs = wx.getStorageSync('logs') || [] logs.unshift(Date.now()) wx.setStorageSync('logs', logs)
log.js - 拉取并处理|格式化日志
this.setData({ logs: (wx.getStorageSync('logs') || []).map(log => { return { date: util.formatTime(new Date(log)), timeStamp: log } }) })
早期版本的API,复合数据的保存和存储需要经过序列化 JSON.stringify 和解析 JSON.parse;现在可以直接使用
同步 | 异步 |
---|---|
wx.setStorage | wx.setStorageSync |
wx.getStorage | wx.getStorageSync |
wx.removeStorage | wx.removeStorageSync |
wx.clearStorage | wx.clearStorageSync |
保存的时候,必须指定key和data
保存成功,返回 errMsg: "setStorage:ok"
wx.setStorage({ key:'msg', data:'hi, there.', success:res=>console.log(res), fail:err=>console.log(err), complete:()=>console.log('set done log') })
获取的时候,必须指定key
如果成功,在返回结果的data中解析数据
如果数据不存在,返回 errMsg: "getStorage:fail data not found"
wx.getStorage({ key:'msg', success:res=>console.log(res), fail:err=>console.log(err), complete:()=>console.log('get done log') })
建议获取数据 get,使用同步调用,减少异步操作带来的性能损耗
.如果数据不存在,返回字符串 hi
getMsgSync() { let msg = wx.getStorageSync('msg') || 'hi' this.setData({ msg: msg }) }
.如果数据不存在,返回对象 {id:100,name:'glpla'}
getMsgSync() { let msg = wx.getStorageSync('msg') || {id:100,name:'glpla'} this.setData({ msg: msg }) }
.如果数据不存在,返回数组 [0, 1, 2, 3, 4]
getMsgSync() { let msg = wx.getStorageSync('msg') || [0, 1, 2, 3, 4] this.setData({ msg: msg }) }
删除的时候,必须指定key
删除成功,返回errMsg: "removeStorage:ok"
wx.removeStorage({ key: 'msg', success:res=>console.log(res), fail:err=>console.log(err), complete:()=>console.log('remove done log') })
清除成功,返回 errMsg: "clearStorage:ok"
wx.clearStorage({ success:res=>console.log(res), fail:err=>console.log(err), complete:()=>console.log('clear done log') })
wx.setStorage({ key: 'obj', data: {id:100,name:'glpla'}, success: res => console.log('set',res), fail: err => console.log('set',err), complete: () => console.log('set done') })
let obj = wx.getStorageSync('obj') || {id:100,name:'glpla'}