Ⅰ 微信小程序怎麼進行數據緩存
在微信小程序中,數據緩存其實就和localstorage 的原理差不多,所以理解起來並不難。下面我們來一起實現一下。
效果圖展示:
我們在index頁面存入數字11,然後在跳轉到新頁面,在將緩存中的11取出渲染到當前頁面。具體代碼如下:
index頁面:
<span style="font-size:24px;">
<view class="btn-area">
<navigator url="../navigator/navigator?title=我是navi">跳轉到新的頁面post情求</navigator>
<navigator url="../redirect/redirect?title=我是red" redirect>跳轉到當前頁面</navigator>
</view>
</span>
<view>
<input style="border:2rpx solid red" placeholder="輸入信息" bindinput="getInput" />
<button style="border:2rpx solid yellow" bindtap="saveInput">存入</button>
</view>1234567891012345678910
index的js:
//index.js
//獲取應用實例
var app = getApp()
Page({
data: {
storage:''
},
onLoad: function () {
var that = this
//獲取輸入值
getInput:function(e){
this.setData({
storage:e.detail.value
})
},
//存儲輸入值
saveInput:function(){
wx.setStorageSync('storage', this.data.storage)
}
})
2223
跳轉頁面:
<view>從存儲中得到的數據:{{storage}}</view>11
跳轉頁面的js:
var app = getApp();
var that;
Page( {
data: {
storage:''
},
onLoad: function(options) {
that = this;
//獲取存儲信息
wx.getStorage({
key: 'storage',
success: function(res){
// success
that.setData({
storage:res.data
})
}
})
}
})
Ⅱ 微信小程序怎麼進行數據緩存
每個微信小程序都可以有自己的本地緩存,可以通過 wx.setStorag(wx.setStorageSync)、wx.getStorage(wx.getStorageSync)、wx.clearStorage(wx.clearStorageSync)可以對本地緩存進行設置、獲取和清理。本地緩存最大為10MB。
注意:
localStorage 是永久存儲的,但是我們不建議將關鍵信息全部存在 localStorage,以防用戶換設備的情況。
wx.setStorage(OBJECT)將數據存儲在本地緩存中指定的 key 中,會覆蓋掉原來該 key 對應的內容,這是一個非同步介面。
代碼示例
wx.setStorage({ key:"key" data:"value" })1234
wx.setStorageSync(KEY,DATA)
將 data 存儲在本地緩存中指定的 key 中,會覆蓋掉原來該 key 對應的內容,這是一個同步介面。
try { wx.setStorageSync('key', 'value') } catch (e) { }1234
wx.getStorageInfo(OBJECT)
非同步獲取當前storage的相關信息
wx.getStorageInfo({ success: function(res) { console.log(res.keys) console.log(res.currentSize) console.log(res.limitSize) } })1234567
wx.getStorageInfoSync
同步獲取當前storage的相關信息
try { var res = wx.getStorageInfoSync() console.log(res.keys) console.log(res.currentSize) console.log(res.limitSize) } catch (e) { // Do something when catch error }12345678
wx.removeStorage(OBJECT)
從本地緩存中非同步移除指定 key 。
wx.removeStorage({ key: 'key', success: function(res) { console.log(res.data) } })123456
wx.removeStorageSync(KEY)
從本地緩存中同步移除指定 key 。 try { wx.removeStorageSync('key') } catch (e) { // Do something when catch error }123456
wx.clearStorage()
清理本地數據緩存。
wx.clearStorage()1
wx.clearStorageSync()
同步清理本地數據緩存
try { wx.clearStorageSync() } catch(e) { // Do something when catch error }
Ⅲ 微信小程序怎麼保存
微信小程序不用保存,只要你使用過一次,就會存在小程序處,下次打開微信後,下拉頂部頁面就會彈出使用過的小程序。