当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 微信小程序学习笔记之本地数据缓存功能详解

微信小程序学习笔记之本地数据缓存功能详解

2019年07月25日  | 移动技术网IT编程  | 我要评论
本文实例讲述了微信小程序学习笔记之本地数据缓存功能。分享给大家供大家参考,具体如下: 前面介绍了。这里再来介绍一下微信小程序的本地数据缓存功能。 【将数据存储在本地

本文实例讲述了微信小程序学习笔记之本地数据缓存功能。分享给大家供大家参考,具体如下:

前面介绍了。这里再来介绍一下微信小程序的本地数据缓存功能。

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

希望本文所述对大家微信小程序开发有所帮助。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网