uni-app 同步缓存 12个小时清除一次缓存信息
最近的项目需求里做了一个缓存查询条件,一个下拉列表式查询,当选择条件完毕后开始缓存当前数据,第二次进入该页面加载缓存,不需要重新选择,比较方便操作,12小时清除一次缓存信息。缓存官网关于缓存的具体讲解同步缓存具体代码同步异步官网关于缓存的具体讲解uni-app官网API同步缓存具体代码uni.getStorageSync(KEY)从本地缓存中同步获取指定 key 对应的内容。uni.setStor
·
官网关于缓存的具体讲解
查询条件缓存规则
- 进入页面,先读取缓存的查询条件
- 缓存存在且未过期,用缓存的查询条件初始化当前页面的查询条件并直接进行查询
- 缓存不存在或已过期,只设置默认查询条件(即日期);存在过期缓存时,需要清除过期的缓存
- 查询条件修改后,都要更新缓存(缓存不存在,创建新的缓存,并记录创建时间)
- 缓存需要有过期时间,过期时长:12小时
同步缓存具体代码
-
uni.getStorageSync(KEY)
从本地缓存中同步获取指定 key 对应的内容。 -
uni.setStorageSync(KEY,DATA)
将 data 存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容,这是一个同步接口。 -
uni.removeStorageSync(KEY)
从本地缓存中同步移除指定 key。
截取片段代码
//加载缓存
onLoad() {
const info = uni.getStorageSync('kqStorage');
if (info){
var before = new Date().getTime() - 12 * 3600 * 1000;
if (before < info.time){
if(info.checkDate){
this.checkDate = info.checkDate;
this.teamId = info.teamId;
this.productOrderId = info.productOrderId;
this.classId = info.classId;
this.filterData = info.filterData
this.defaultIndex = info.defaultIndex;
this.procedureId = info.procedureId
this.queryByInput();
}else{
this.checkDate = util.getDate().fullDate;//不选择为默认系统日期
uni.removeStorageSync('kqStorage')
}
}
}
},
methods:{
//条件查询 简写 主要放缓存代码
getTableList: function() {
that.$http.get('/workshop/staffdaycheckitem/page', params, {}).then(function(response) {
//这里只会在接口是成功状态返回
that.tableList = response.records
that.total = response.total
var storage = {
'teamId':that.teamId,
'productOrderId':that.productOrderId,
'classId':that.classId,
'checkDate':that.checkDate,
'time': (new Date()).getTime(),
'filterData':that.filterData,
'defaultIndex':that.defaultIndex,
'procedureId':that.procedureId,
}
uni.setStorageSync('kqStorage', storage);
}).catch(function(error) {
//这里只会在接口是失败状态返回,不需要去处理错误提示
console.log(error);
});
},
}
同步异步
因为涉及到同步缓存和异步缓存,简单记一下同步与异步的区别。
- 同步方法调用一旦开始,调用者必须等到方法调用返回后,才能继续后续的行为。
- 异步方法调用更像一个消息传递,一旦开始,方法调用就会立即返回,调用者就可以继续后续的操作。而,异步方法通常会在另外一个线程中,“真实”地执行着。整个过程,不会阻碍调用者的工作。
- 异步执行
- 同步执行
更多推荐
已为社区贡献1条内容
所有评论(0)