一. 数据缓存到本地
微信提供了两种方式:缓存
异步方式将数据缓存在本地缓存中指定的key中
会覆盖原来该key对应的内容
单个key容许存储的最大数据长度为1MB微信
key | string | 本地缓存中指定的key |
---|---|---|
data | any | 须要存储的内容 |
Page({ onload:function(){ var user = this.getUserInfo(); console.log(user); wx.getStorage({ key:'user', data:user, success:function(res){ console.log(res); } }) }, getUserInfo:function(){//自定义函数 var user = new Object(); user.name = 'xiaogang'; user.sex = 'boy'; user.age = 18; user.address = 'beijing'; return user; } })
同步的方式将数据存储在本地指定的key中
会覆盖原来该key的内容
相比于异步缓存数据它更简单异步
key | string | 本地缓存中指定的key |
---|---|---|
data | Object/String | 须要存储的内容。只支持原生类型、Data、及可以经过JSON.stringify序列化的对象 |
Page({ onload:function(){ var userSync = this.getUserInfo(); wx.setStorageSync('userSync',userSync) }, getUserInfo:function(){//自定义函数 var user = new Object(); user.name = 'xiaogang'; user.sex = 'boy'; user.age = 18; user.address = 'beijing'; return user; } })
二. 获取本地缓存数据
微信提供了四个API函数
1.wx.getStorage(OBJECT)大数据
使用异步方式从本地缓存中获取指定的key对应的内容this
key | string | 本地缓存中指定的key |
---|
2.wx.getStorageSync(OBJECT)code
同步接口,用来从本地缓存中同步获取指定的key对应的内容对象
key | string | 本地缓存中指定的key |
---|
Page({ onLoad:function(){ var userSync = wx.getStorageSync('userSync'); console.log(userSync); } })
Page({ onLoad:function(){ wx.getStorageInfo({ success:function(res){ console.log(res) } }) } })
Page({ onLoad:function(){ var storage = wx.getStorageInfoSync(); console.log(storage); } })
三. 移除和清理本地缓存数据
微信提供四个接口:接口
1.wx.removeStorage(OBJECT)rem
从本地缓存中移除指定key
2.wx.removeStorageSync(KEY)
从本地缓存中移除指定key
3.wx.clearStorage()
清理本地数据缓存
4.wx.clearStorageSync()
清理本地数据缓存