微信小程序 Storage API實(shí)例詳解

其實(shí)這個(gè)存儲(chǔ)在新建Demo的時(shí)候就已經(jīng)用到了就是存儲(chǔ)就是那個(gè)logs日志,數(shù)據(jù)存儲(chǔ)主要分為同步和異步
異步存儲(chǔ)方法:
存數(shù)據(jù)
wx.setStorage(object) 相同key會(huì)覆蓋,可寫回調(diào)方法

獲取方法:
wx.getStorage(object)

清除方法:
wx.clearStorage()里面可以寫回調(diào)函數(shù) 成功,失敗,完成
同步存儲(chǔ)方法:
存數(shù)據(jù) 相同key會(huì)覆蓋
wx.setStorageSync(key,data)
讀數(shù)據(jù)
wx.getStorageSync(key) 存儲(chǔ)是指定的key
清除數(shù)據(jù)
wx.clearStorageSync() 不可寫回調(diào)方法
wxml
<!--動(dòng)態(tài)獲取數(shù)據(jù)-->
<text>{{storageContent}}</text>
<!--存-->
<button type="primary" bindtap="listenerStorageSave">storage存儲(chǔ)信息會(huì)在text上顯示</button>
<!--取-->
<button type="primary" bindtap="listenerStorageGet">獲取storage存儲(chǔ)的信息</button>
<!--清-->
<button type="warn" bindtap="listenerStorageClear">清楚異步存儲(chǔ)數(shù)據(jù)</button>
<text>{{storageSyncContent}}</text>
<button type="primary" bindtap="listenerStorageSyncSave">storageSync存儲(chǔ)信息會(huì)在text上顯示</button>
<button type="primary" bindtap="listenerStorageSyncGet">獲取storageSync存儲(chǔ)信息</button>
<button type="warn" bindtap="listenerStorageSyncClear">清除同步存儲(chǔ)數(shù)據(jù)</button>
js
Page({
data:{
// text:"這是一個(gè)頁面"
storageContent: '',
storageSyncContent: ''
},
onLoad:function(options){
// 頁面初始化 options為頁面跳轉(zhuǎn)所帶來的參數(shù)
},
/**
* 異步存儲(chǔ)
*/
listenerStorageSave: function() {
//以鍵值對(duì)的形式存儲(chǔ) 傳進(jìn)去的是個(gè)對(duì)象
wx.setStorage({
key: 'key',
data: '我是storeage異步存儲(chǔ)的信息',
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
})
},
/**
* 失敗會(huì)調(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ù)同步存儲(chǔ)
*/
listenerStorageSyncSave: function() {
wx.setStorageSync('key', '我是同步存儲(chǔ)的數(shù)據(jù)')
},
/**
* 數(shù)據(jù)同步獲取
*/
listenerStorageSyncGet: function() {
// var that = this;
var value = wx.getStorageSync('key')
this.setData({
storageSyncContent: value
})
},
/**
* 清除同步存儲(chǔ)數(shù)據(jù)
*/
listenerStorageSyncClear: function() {
wx.clearStorageSync()
},
onReady:function(){
// 頁面渲染完成
},
onShow:function(){
// 頁面顯示
},
onHide:function(){
// 頁面隱藏
},
onUnload:function(){
// 頁面關(guān)閉
}
})
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
相關(guān)文章
詳解Jest?如何支持異步及時(shí)間函數(shù)實(shí)現(xiàn)示例
前端canvas中物體邊框和控制點(diǎn)的實(shí)現(xiàn)示例
js前端架構(gòu)Git?commit提交規(guī)范

