溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

微信小程序中如何實現(xiàn)本地數(shù)據(jù)緩存功能

發(fā)布時間:2021-07-09 14:10:02 來源:億速云 閱讀:138 作者:小新 欄目:web開發(fā)

小編給大家分享一下微信小程序中如何實現(xiàn)本地數(shù)據(jù)緩存功能,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!

具體如下:

前面介紹了微信小程序獲取位置信息操作。這里再來介紹一下微信小程序的本地數(shù)據(jù)緩存功能。

【將數(shù)據(jù)存儲在本地緩存】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'] = '參數(shù)錯誤';
  }
  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 () { }
  })
 }
})

實現(xiàn)緩存的存儲和讀?。?/p>

微信小程序中如何實現(xiàn)本地數(shù)據(jù)緩存功能

【從緩存中移除指定數(shù)據(jù)】wx.removeStorage

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

 【清除全部緩存數(shù)據(jù)】wx.clearStorage

wx.clearStorage()

看完了這篇文章,相信你對“微信小程序中如何實現(xiàn)本地數(shù)據(jù)緩存功能”有了一定的了解,如果想了解更多相關知識,歡迎關注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。

AI