官网关于缓存的具体讲解

uni-app官网API

查询条件缓存规则

  1. 进入页面,先读取缓存的查询条件
  2. 缓存存在且未过期,用缓存的查询条件初始化当前页面的查询条件并直接进行查询
  3. 缓存不存在或已过期,只设置默认查询条件(即日期);存在过期缓存时,需要清除过期的缓存
  4. 查询条件修改后,都要更新缓存(缓存不存在,创建新的缓存,并记录创建时间)
  5. 缓存需要有过期时间,过期时长:12小时
    在这里插入图片描述

同步缓存具体代码

  1. uni.getStorageSync(KEY)
    从本地缓存中同步获取指定 key 对应的内容。

  2. uni.setStorageSync(KEY,DATA)
    将 data 存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容,这是一个同步接口。

  3. 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. 同步方法调用一旦开始,调用者必须等到方法调用返回后,才能继续后续的行为。
  2. 异步方法调用更像一个消息传递,一旦开始,方法调用就会立即返回,调用者就可以继续后续的操作。而,异步方法通常会在另外一个线程中,“真实”地执行着。整个过程,不会阻碍调用者的工作。
  3. 异步执行
    异步执行
  4. 同步执行
    在这里插入图片描述
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐