
简述
小程序获取设置缓存,支持过期时间,内容存储在storge中
主要代码
/**
* 缓存类
* @param content
* @returns {boolean}
*/
function cache(name,data,expires_in) {
if(!name)
return;
if(!expires_in)expires_in=60*60*24;//默认缓存时间1天
var timestamp = parseInt(Date.parse(new Date())/1000);
if(!data){//获取缓存
var cache = wx.getStorageSync(name);
if(!cache)
return '';
var content='';
if (cache.time >= timestamp && cache.content) {//判断缓存有效期
content=cache.content;
} else {
wx.removeStorageSync(name)
}
return content;
}else{//存储缓存
var cachetime= timestamp + expires_in;
var cache={'time': cachetime, 'content': data};
return wx.setStorageSync(name, cache);
}
}
module.exports = {
cache: cache,
}
使用示例
先引入
var cache = require("../../utils/cache.js");
获取 cache.cache('name');
设置 cache.cache('name','value',3600);
getSlideList() {
var that = this;
var slide = cache.cache('slide');
if (slide) {
that.setData({
slideList: slide,
})
} else {
request.GET('slide', '',
function (res) {
if (res.data.code == 0) {
that.setData({
slideList: res.data.data.data,
})
cache.cache('slide',res.data.data.data);
}
},function (error) {
console.log(error);
})
}
},
版权声明:本文为weixin_34219634原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。