Uni-app 缓存工具函数

该工具函数提供以下功能:

  • setCache(key, value, expire):将指定数据保存到缓存中
  • getCache(key, defaultValue):从缓存中获取指定键名的数据
  • removeCache(key):移除指定键名的缓存数据

函数列表

| 函数名称 | 函数描述 | 参数 | 返回值 | |---|---|---|---| | setCache | 将指定数据保存到缓存中 | - key: 缓存键名
- value: 缓存值
- expire: 过期时间(单位:秒),默认为 -1 表示永不过期 | 无 | | getCache | 从缓存中获取指定键名的数据 | - key: 缓存键名
- defaultValue: 默认值,如果缓存中不存在或已过期,则返回该默认值 | 缓存中的值或默认值 | | removeCache | 移除指定键名的缓存数据 | - key: 缓存键名 | 无 |

代码示例

/**
 * 缓存前缀,用于避免与其他缓存键名冲突
 */
const CACHE_PREFIX = 'uni_cache_';

/**
 * 将指定数据保存到缓存中
 * @param {string} key 缓存键名
 * @param {*} value 缓存值
 * @param {number} expire 过期时间(单位:秒),默认为 -1 表示永不过期
 */
export function setCache(key, value, expire = -1) {
   // 构造完整的缓存键名
   const cacheKey = CACHE_PREFIX + key;

   // 构造缓存值对象,包含数据和过期时间
   const cacheValue = {
      data: value,
      expire: expire > 0 ? Date.now() + expire * 1000 : -1,
   };

   // 将缓存值保存到本地缓存中
   uni.setStorageSync(cacheKey, cacheValue);
}

/**
 * 从缓存中获取指定键名的数据
 * @param {string} key 缓存键名
 * @param {*} defaultValue 默认值,如果缓存中不存在或已过期,则返回该默认值
 * @returns {*} 缓存中的值或默认值
 */
export function getCache(key, defaultValue = null) {
   // 构造完整的缓存键名
   const cacheKey = CACHE_PREFIX + key;

   // 从本地缓存中获取缓存值
   const cacheValue = uni.getStorageSync(cacheKey);

   // 如果存在缓存值且未过期,则返回缓存数据;否则移除缓存并返回默认值
   if (cacheValue) {
      if (cacheValue.expire === -1 || cacheValue.expire > Date.now()) {
         return cacheValue.data;
      } else {
         removeCache(key);
      }
   }

   return defaultValue;
}

/**
 * 移除指定键名的缓存数据
 * @param {string} key 缓存键名
 */
export function removeCache(key) {
   // 构造完整的缓存键名
   const cacheKey = CACHE_PREFIX + key;

   // 从本地缓存中移除指定键名的缓存数据
   uni.removeStorageSync(cacheKey);
}
Uni-app 缓存工具函数 - setCache、getCache、removeCache

原文地址: https://www.cveoy.top/t/topic/lLf1 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录