W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
解釋:同步獲取當(dāng)前 storage 的相關(guān)信息。
無(wú)
<view class="container">
<view class="card-area">
<view class="list-area border-bottom">
<label class="list-item-key-4">key</label>
<input class="list-item-value" bindfocus="keyFocus" bindinput="keyInput" type="text" value="{{key}}" placeholder="請(qǐng)輸入key" />
</view>
<view class="list-area border-bottom">
<label class="list-item-key-4">value</label>
<input class="list-item-value" bindfocus="valueFocus" bindinput="valueInput" type="text" value="{{value}}" placeholder="請(qǐng)輸入value" />
</view>
<view>
<button bindtap="setStorage" type="primary" hover-stop-propagation="true">存儲(chǔ)數(shù)據(jù)</button>
<button bindtap="getStorage" type="primary" hover-stop-propagation="true" disabled="{{disabled}}">讀取數(shù)據(jù)</button>
<button bindtap="getStorageInfo" type="primary" disabled="{{disabled}}">獲取存儲(chǔ)數(shù)據(jù)信息</button>
</view>
</view>
</view>
Page({
data: {
key: '示例Key',
value: '示例Value',
disabled: true
},
keyInput(e) {
this.setData('key', e.detail.value);
},
valueInput(e) {
this.setData('value', e.detail.value);
},
valueFocus() {
this.setData('value', '');
},
keyFocus() {
this.setData('key', '');
},
setStorage() {
let key = this.hasKey();
if (!key) {
return;
}
swan.setStorage({
key,
data: this.getData('value'),
success: res => {
this.toast('存儲(chǔ)成功', 'none');
this.setData('disabled', false);
},
fail: err => {
this.toast('存儲(chǔ)數(shù)據(jù)失敗');
}
});
},
getStorage() {
let key = this.hasKey();
if (!key) {
return;
}
swan.getStorage({
key,
success: res => {
const data = res.data;
if (data) {
swan.showModal({
title: '數(shù)據(jù)信息',
content: `${key}: ${data}`,
showCancel: false
});
} else {
this.toast('找不到key對(duì)應(yīng)的值');
}
},
fail: err => {
this.toast('讀取數(shù)據(jù)失敗');
}
});
},
getStorageInfo() {
let res = swan.getStorageInfoSync();
// 基礎(chǔ)庫(kù) 3.140.1 之前,無(wú)法判斷接口是否調(diào)用失敗
// 基礎(chǔ)庫(kù) 3.140.1 及以后,通過(guò) instanceof 來(lái)判斷接口是否調(diào)用失敗
if (!(res instanceof Error)) {
console.log('getStorageInfoSync success', res);
}
else {
console.log('getStorageInfoSync fail', res.message);
}
},
hasKey() {
let key = this.getData('key');
if (key) {
return key;
}
this.toast('key不能為空');
},
toast(title, icon = 'none') {
swan.showToast({title, icon});
}
});
error
對(duì)象,可通過(guò)instanceof
來(lái)判斷接口是否調(diào)用失敗。錯(cuò)誤碼 | 說(shuō)明 |
---|---|
1001 |
執(zhí)行失敗 |
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: