1. 程式人生 > >微信小程式把玩(三十六)Storage API

微信小程式把玩(三十六)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(){
    // 頁面關閉
  }
})