本來想叫“小程序的特點”,但是轉念一想,前端HTML(5)現在也加入了localStorage和sessionStorage的本地緩存操作,這並不是小程序獨有的。但不得不說,作爲移動端運行的程序,小程序的本地緩存要比網頁端的HTML5好多了(更安全)。
小程序的緩存仍然是用了set/get-Stroage的方法:
(app.js)
var dataObj=require("data/data.js");
App({
onLaunch:function(){
wx.setStorage({
key:'postList',
data:dataObj.postList,
success:function(){
//success操作
},
fail:function(){
//fail操作
},
complate:function(){
//無論成功或失敗都會調用
}
})
},
})
在代碼裏,首先通過require加載了data.js文件裏的數據。然後在程序 生命週期函數 onLaunch 裏 ,使用wx.setStorage方法將數據存入小程序的緩存中。
(帶有wx.前綴的方法都是小程序提供的api)
什麼是生命週期?
上一篇文章 說過,小程序與vue“難解難分”,那麼,小程序當中也有一些用於監聽小程序運行狀態的函數,在指定時刻 自行調用 :
- onLaunch :監聽小程序初始化,全局只觸發一次,在小程序頁面初始化完成後
- onShow :監聽小程序顯示,當小程序啓動,或從後臺進入前臺顯示時觸發
- onHide :監聽小程序隱藏,當小程序從前臺進入後臺時觸發
- onError :錯誤監聽函數,當小程序發生腳本錯誤,或者API調用失敗時觸發,並帶上錯誤信息
小程序緩存永久存在,不會過期,只能手動清除:wx.removeStorage或wx.clearStorage方法,緩存以key:value鍵值對形式存在,容量不超過10MB
setStorage是異步方法,這對於性能和體驗來說是非常不錯的,但在日常試驗中,還是推薦同步方法:setStorageSync,可以降低代碼風險率和調試難度。當然,任何異步方法都有同步方法
上面代碼在實際開發完成後,還可以加一句判斷(這裏爲省事用同步方法):
App({
onLaunch:function(){
var storageData=wx.getStorageSync('postList');
if(!storageData){
var dataObj=require("data/data.js");
wx.clearStorageSync();
wx.setStorageSync('postList',dataObj.postList);
}
},
})
這樣做可以避免每次啓動應用程序都重複初始化數據庫。(但在開發過程中,爲了避免麻煩,可以不要if,就不用每次手動更新了)
擴展 - 面向對象
ES6-Class和prototype編寫緩存類:
(DBPost.js)
var DBPost=function(){
this.storageKeyName='postList'; //所有文章本地緩存存儲鍵值 - 這裏postList可以自己定義
}
DBPost.prototype={
getAllPostData:function(){
var res=wx.getStorageSync(this.storageKeyName);
if(!res){
res=require("../data/data.js").postList; //直接取出數據集合(不去操作對象了)
this.execSetStorageSync(res);
}
return res;
},
//本地緩存,保存更新
execSetStorageSync:function(data){
wx.setStorageSync(this.storageKeyName,data);
},
};
module.exports={
DBPost:DBPost
};
這一點倒是更符合js原型(鏈)的特點了:
<script> function Elem(id) { this.elem=document.getElementById(id); } Elem.prototype.html=function (val) { var elem=this.elem; if(val){ elem.innerHTML=val; //return this; }else{ return elem.innerHTML; } }; Elem.prototype.on=function (type,fn) { var elem=this.elem; elem.addEventListener(type,fn); }; var div1=new Elem('div1'); div1.html('<p>hello mxc</p>').on('click',function () { alert('clicked'); }).html('<p>hello javascript</p>'); </script>
使用緩存類:
(post.js)
var DBPost=require('../../db/DBPost.js').DBPost; //加載DBPost文件,並取出DBPost
Page({
data:{
},
onLoad:function(){
var dbPost=new DBPost(); //因爲DBPost是函數(有顯式原型prototype的是函數),所以要使用它必須先用操作符new將DBPost實例化
this.setData({
postList:dbPost.getAllPostData() //postList是數據文件post.js裏的集合對象
});
},
})
如果第一行是 var DBPost=require('../../db/DBPost.js')
,只怕代碼第六行就要這麼寫:var dbPost=new DBPost.DBPost();
了