微信小程序 Storage API實例詳解
其實這個存儲在新建Demo的時候就已經(jīng)用到了就是存儲就是那個logs日志,數(shù)據(jù)存儲主要分為同步和異步
異步存儲方法:
存數(shù)據(jù)
wx.setStorage(object) 相同key會覆蓋,可寫回調(diào)方法
獲取方法:
wx.getStorage(object)
清除方法:
wx.clearStorage()里面可以寫回調(diào)函數(shù) 成功,失敗,完成
同步存儲方法:
存數(shù)據(jù) 相同key會覆蓋
wx.setStorageSync(key,data)
讀數(shù)據(jù)
wx.getStorageSync(key) 存儲是指定的key
清除數(shù)據(jù)
wx.clearStorageSync() 不可寫回調(diào)方法
wxml
<!--動態(tài)獲取數(shù)據(jù)--> <text>{{storageContent}}</text> <!--存--> <button type="primary" bindtap="listenerStorageSave">storage存儲信息會在text上顯示</button> <!--取--> <button type="primary" bindtap="listenerStorageGet">獲取storage存儲的信息</button> <!--清--> <button type="warn" bindtap="listenerStorageClear">清楚異步存儲數(shù)據(jù)</button> <text>{{storageSyncContent}}</text> <button type="primary" bindtap="listenerStorageSyncSave">storageSync存儲信息會在text上顯示</button> <button type="primary" bindtap="listenerStorageSyncGet">獲取storageSync存儲信息</button> <button type="warn" bindtap="listenerStorageSyncClear">清除同步存儲數(shù)據(jù)</button>
js
Page({ data:{ // text:"這是一個頁面" storageContent: '', storageSyncContent: '' }, onLoad:function(options){ // 頁面初始化 options為頁面跳轉(zhuǎn)所帶來的參數(shù) }, /** * 異步存儲 */ listenerStorageSave: function() { //以鍵值對的形式存儲 傳進去的是個對象 wx.setStorage({ key: 'key', data: '我是storeage異步存儲的信息', success: function(res) { console.log(res) } }) }, /** * 異步取信息 */ listenerStorageGet: function() { var that = this; wx.getStorage({ //獲取數(shù)據(jù)的key key: 'key', success: function(res) { console.log(res) that.setData({ // storageContent: res.data }) }, /** * 失敗會調(diào)用 */ fail: function(res) { console.log(res) } }) }, /** * 清除數(shù)據(jù) */ listenerStorageClear: function() { var that = this; wx.clearStorage({ success: function(res) { that.setData({ storageContent: '' }) } }) }, /** * 數(shù)據(jù)同步存儲 */ listenerStorageSyncSave: function() { wx.setStorageSync('key', '我是同步存儲的數(shù)據(jù)') }, /** * 數(shù)據(jù)同步獲取 */ listenerStorageSyncGet: function() { // var that = this; var value = wx.getStorageSync('key') this.setData({ storageSyncContent: value }) }, /** * 清除同步存儲數(shù)據(jù) */ listenerStorageSyncClear: function() { wx.clearStorageSync() }, onReady:function(){ // 頁面渲染完成 }, onShow:function(){ // 頁面顯示 }, onHide:function(){ // 頁面隱藏 }, onUnload:function(){ // 頁面關(guān)閉 } })
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章

詳解Jest?如何支持異步及時間函數(shù)實現(xiàn)示例

js前端架構(gòu)Git?commit提交規(guī)范