1. 程式人生 > >微信小程式學習筆記(八)本地資料快取

微信小程式學習筆記(八)本地資料快取

上一篇:微信小程式學習筆記(七)

【將資料儲存在本地快取】wx.setStorage

【讀取本地快取】wx.getStorage

以手機號+密碼登入為例,把登入成功返回的token值儲存在本地快取中,然後讀取快取中的token:

login.php:

<?php 
    header("Content-type:text/html;charset=utf-8");
    $arr = array("state"=>0,"data"=>array(),"msg"=>'');
    $phone = $_POST['phone'];
    $password = $_POST['password'];
    if($phone && $password){
	//省略驗證......

	//返回登入token
	$tokenstr = 'liweishan666';
	$token = $phone.time().$tokenstr;//省略加密

	$arr['state'] = 1;
	$arr['msg'] = '登入成功';
	$arr['data']['token'] = $token;
    }else{
	$arr['msg'] = '引數錯誤';
    }
    echo json_encode($arr);
    die;
	

login.wxml:

<form bindsubmit="formSubmit" bindreset="formReset">
  <view>
    手機號:<input type="text" name="phone" placeholder="請輸入賬號" confirm-type="done" />
    密碼:<input password type="number" name="password" placeholder="請輸入6位密碼" maxlength="6" />
  </view>
  <view class="btn-area">
    <button formType="submit">登入</button>
  </view>

  <view class="btn-area">
    <button bindtap="gettoken">讀取快取token</button>
  </view>

  <view class="btn-area">{{token}}</view>
</form>

login.js:

Page({
  formSubmit: function (e) {
    wx.request({
      url: 'https://www.msllws.top/login.php',
      data: {
        'phone': e.detail.value.phone,
        'password': e.detail.value.password
      },
      method: 'POST',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        console.log(res.data);
        //以鍵值對的形式儲存到本地快取
        wx.setStorage({
          key: "token",
          data: res.data.data.token
        })
      },
      fail: function () { },
      complete: function () { }
    })
  },

  gettoken: function (e) {
    var that = this
    wx.getStorage({
      key: 'token',
      success: function (res) {
        that.setData({'token': res.data})
      },
      fail: function () { },
      complete: function () { }
    })
  }
})

實現快取的儲存和讀取:


【從快取中移除指定資料】wx.removeStorage

wx.removeStorage({
  key: 'token',
  success (res) {
    console.log(res.data)
  } 
})

 【清除全部快取資料】wx.clearStorage

wx.clearStorage()