一. 數據緩存到本地
微信提供了兩種方式:緩存
異步方式將數據緩存在本地緩存中指定的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()
清理本地數據緩存