微信小程序?qū)W習(xí)筆記之本地數(shù)據(jù)緩存功能詳解
本文實例講述了微信小程序?qū)W習(xí)筆記之本地數(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>

【從緩存中移除指定數(shù)據(jù)】wx.removeStorage
wx.removeStorage({
key: 'token',
success (res) {
console.log(res.data)
}
})
【清除全部緩存數(shù)據(jù)】wx.clearStorage
wx.clearStorage()
希望本文所述對大家微信小程序開發(fā)有所幫助。
相關(guān)文章
setinterval()與clearInterval()JS函數(shù)的調(diào)用方法
這篇文章主要介紹了setinterval()與clearInterval()JS函數(shù)的調(diào)用方法,實例分析了setinterval()與clearInterval()的語法結(jié)構(gòu)及使用技巧,需要的朋友可以參考下2015-01-01
詳解JS如何使用Promise緩存網(wǎng)絡(luò)請求
網(wǎng)絡(luò)請求是現(xiàn)代Web應(yīng)用中的常見操作,很多時候需要獲取服務(wù)器上的數(shù)據(jù),在進行網(wǎng)絡(luò)請求時,為了減輕服務(wù)器的壓力,緩存策略常被用來避免對同一數(shù)據(jù)的重復(fù)請求,本文將探討如何使用Promise結(jié)合緩存來高效處理網(wǎng)絡(luò)請求,需要的朋友可以參考下2023-12-12

