在uniapp中设置缓存过期时间通常涉及到本地存储的操作。你可以使用uni.setStorageSync或uni.setStorage来设置缓存项,并结合JavaScript的Date对象来计算过期时间。
以下是一个示例代码,展示如何设置缓存并在一定时间后过期:
// 设置缓存
function setCache(key, value, expireSeconds) {
const currentTime = Date.now();
const expireTime = currentTime + expireSeconds * 1000; // 转换为毫秒
uni.setStorage({
key: key,
data: {
value: value,
expireTime: expireTime
},
success: function() {
console.log('缓存设置成功');
}
});
}
// 获取缓存
function getCache(key) {
const res = uni.getStorageSync(key);
if (res && res.expireTime > Date.now()) {
return res.value;
} else {
uni.removeStorage({
key: key,
success: function() {
console.log('缓存已过期,已移除');
}
});
return null; // 缓存过期,返回null
}
}
// 使用示例
const key = 'myCacheKey';
const value = 'myCacheValue';
const expireSeconds = 30; // 缓存30秒
setCache(key, value, expireSeconds);
// 稍后获取缓存
const cachedValue = getCache(key);
console.log(cachedValue); // 缓存过期时会打印null
在这个示例中,setCache函数接受一个键、值和过期时间(秒),然后将值与过期时间存储在一起。getCache函数用于检查缓存是否过期,如果没有过期则返回值,如果过期则移除缓存并返回null。