微信小程序把玩(三十六)Storage API

這裏寫圖片描述

其實這個存儲在新建Demo的時候就已經用到了就是存儲就是那個logs日誌,數據存儲主要分爲同步和異步

異步存儲方法:

存數據
wx.setStorage(object) 相同key會覆蓋,可寫回調方法

這裏寫圖片描述

獲取方法:

wx.getStorage(object)

這裏寫圖片描述

清除方法:

wx.clearStorage()裏面可以寫回調函數 成功,失敗,完成

同步存儲方法:

存數據 相同key會覆蓋

wx.setStorageSync(key,data)

讀數據

wx.getStorageSync(key) 存儲是指定的key

清除數據

wx.clearStorageSync() 不可寫回調方法

wxml

<!--動態獲取數據-->
<text>{{storageContent}}</text>
<!--存-->
<button type="primary" bindtap="listenerStorageSave">storage存儲信息會在text上顯示</button>
<!--取-->
<button type="primary" bindtap="listenerStorageGet">獲取storage存儲的信息</button>
<!--清-->
<button type="warn" bindtap="listenerStorageClear">清楚異步存儲數據</button>


<text>{{storageSyncContent}}</text>
<button type="primary" bindtap="listenerStorageSyncSave">storageSync存儲信息會在text上顯示</button>
<button type="primary" bindtap="listenerStorageSyncGet">獲取storageSync存儲信息</button>
<button type="warn" bindtap="listenerStorageSyncClear">清除同步存儲數據</button>

js

Page({
  data:{
    // text:"這是一個頁面"
    storageContent: '',
    storageSyncContent: ''
  },
  onLoad:function(options){
    // 頁面初始化 options爲頁面跳轉所帶來的參數
  },
  /**
   * 異步存儲
   */
  listenerStorageSave: function() {
    //以鍵值對的形式存儲 傳進去的是個對象
    wx.setStorage({
      key: 'key',
      data: '我是storeage異步存儲的信息',
      success: function(res) {
        console.log(res)
      }
    })
  },
  /**
   * 異步取信息
   */
  listenerStorageGet: function() {
    var that = this;
    wx.getStorage({
      //獲取數據的key
      key: 'key',
      success: function(res) {
        console.log(res)
        that.setData({
          //
          storageContent: res.data
        })
      },
      /**
       * 失敗會調用
       */
      fail: function(res) {
        console.log(res)
      }
    })
  },

  /**
   * 清除數據
   */
  listenerStorageClear: function() {
    var that = this;
    wx.clearStorage({
      success: function(res) {
        that.setData({
          storageContent: ''
        })
      }
    })
  },


  /**
   * 數據同步存儲
   */
  listenerStorageSyncSave: function() {
    wx.setStorageSync('key', '我是同步存儲的數據')
  },

  /**
   * 數據同步獲取
   */
  listenerStorageSyncGet: function() {
    // var that = this;
    var value = wx.getStorageSync('key')
    this.setData({
      storageSyncContent: value
    })
  },

  /**
   * 清除同步存儲數據
   */
  listenerStorageSyncClear: function() {
    wx.clearStorageSync()
  },

  onReady:function(){
    // 頁面渲染完成
  },
  onShow:function(){
    // 頁面顯示
  },
  onHide:function(){
    // 頁面隱藏
  },
  onUnload:function(){
    // 頁面關閉
  }
})
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章