小程序之数据缓冲的封装
未使用缓冲的请求
将请求添加到小程序的生命周期函数,每次加载数据都会请求数据。
Page({
data : {
imgList: []
},
onLoad: function() {
carouselModel.getAll((res) => {
let imgList = res.object;
this.setData({ imgList });
})
}
})
使用缓冲之后
每次加载页面都会发送请求,很多不经常需要加载的数据频繁的请求服务器很浪费资源。将数据添加在小程序的缓冲中,可以节省很多不必要的数据请求。
封装小程序的缓冲api接口函数
/**
* 设置数据缓冲时间
*/
class TimeStorage {
constructor() {
this.deepTime = "_deepTime";
}
// 存储某一缓冲数据
putStorage(k, v, t = 0) {
// 保存数据到缓冲中
wx.setStorageSync(k, v);
// 判断是否添加失效时间
if (t > 0) {
// 获取当前时间
let timestamp = Date.parse(new Date());
// 添加失效时间
timestamp = timestamp / 1000 + parseInt(t);
console.log("添加失效时间");
console.log(timestamp);
// 保存失效时间到缓冲中
wx.setStorageSync(k + this.deepTime, timestamp.toString());
}
}
// 获取某一缓冲数据
getStorage(k) {
// 获取当前时间
let timeNow = Date.parse(new Date()) / 1000;
// 获取失效时间
let loseTime = parseInt(wx.getStorageSync(k + this.deepTime));
console.log("获取失效时间");
console.log(loseTime);
console.log("获取当前时间");
console.log(timeNow);
// 判断失效时间是否已存在
if (loseTime) {
// 判断当前时间和失效时间是否过期
if (loseTime > timeNow) {
// 获取缓冲的数据
let res = wx.getStorageSync(k);
return res ? res : '';
}else {
this.removeStorage(k);
return '';
}
}else {
let res = wx.getStorageSync(k);
return res ? res : '';
}
}
// 移除某一缓冲数据
removeStorage(k) {
// 清除缓冲数据
wx.removeStorage({key: k});
// 清除缓冲失效时间
wx.removeStorage({key: k + this.deepTime});
}
// 清除所有缓冲
clearStorage() {
wx.clearStorage();
}
}
export { TimeStorage }
使用
import { CarouselModel } from "../../models/CarouselModel.js"
import { TimeStorage } from '../../utils/timeStorage.js'
let carouselModel = new CarouselModel()
let timeStorage = new TimeStorage()
Page({
data : {
imgList: []
},
onLoad: function() {
// 判断缓冲中是否有数据
let imgListStorage = timeStorage.getStorage('carousel');
console.log(imgListStorage);
// 使用缓冲
if (imgListStorage != ''){
this.setData({ imgList: imgListStorage });
}else{
// 没有缓冲发送请求
carouselModel.getAll((res) => {
let imgList = res.object;
// 添加数据到缓冲,并设置失效时间为1天
timeStorage.putStorage('carousel', imgList, 60*60*24);
this.setData({ imgList });
})
}
}
})
初次请求
缓冲 | 请求 |
---|---|
再次编译小程序
缓冲 | 请求 |
---|---|