微信小程序学习笔记(八)本地数据缓存

版权声明:转载请注明出处,谢谢。 https://blog.csdn.net/msllws/article/details/83992384

上一篇:微信小程序学习笔记(七)

【将数据存储在本地缓存】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()

猜你喜欢

转载自blog.csdn.net/msllws/article/details/83992384