微信开发 缓存页面内容
1.获取想要缓存的数据
关于request请求封装请查看我的上一篇文章
封装全局request请求
getCates() {
wx.get('/categories')
.then((res) => {
let cates = res.map(v=>v.cat_name)
let allcates = res
let rightContent = res[0].children
wx.setStorageSync("cates",{time:Date.now(),data:allcates}) // 关键代码
this.setData({
cates,
rightContent,
allcates
})
})
.catch((err) => {
console.log(err)
})
},
2. 查看此数据之前有没有缓存
3.缓存是否过期
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
// 缓存数据
const Cates = wx.getStorageSync('cates')
if(!Cates){
// 无缓存
this.getCates()
}else{
// 有缓存
// 时间过期
if(Date.now()-Cates.time>1000*10){
this.getCates()
}else{
// 有缓存
// 时间没有过期
this.data.allcates = Cates.data
let cates = this.data.allcates.map(v=>v.cat_name)
let rightContent = this.data.allcates[0].children
this.setData({
cates,
rightContent,
allcates:Cates.data
})
}
}
},
主要的逻辑思路: 获取数据并保存到storage中wx.setStorageSync("cates",{time:Date.now(),data:allcates})
在onload()
函数中分为第一次加载和已加载过一次两种情况:
第一种通过判断storage中的key是否存在,存在则有缓存,不存在则发请求。
第二种情况已有缓存,判断时间是否过期,过期重新发请求,未过期则读取缓存数据const Cates = wx.getStorageSync('cates')
注意 :微信开发中的存储和vue是有区别的,vue中调用存储,vue的内部第一步是调取tostring方法将数据转为字符串,所以对于对象的存储需要特殊处理。微信更为简单不需要转化。