12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- const cacheManager = (function() {
- const STORAGE_PREFIX = 'App_cache_';
- function set(key, value) {
- const fullKey = STORAGE_PREFIX + key;
- if (typeof value === 'object' && value !== null) {
- // 如果是对象,则将其转换为字符串存储
- uni.setStorageSync(fullKey, JSON.stringify(value));
- } else {
- uni.setStorageSync(fullKey, value);
- }
- }
- // 获取缓存
- function get(key) {
- const fullKey = STORAGE_PREFIX + key;
- const value = uni.getStorageSync(fullKey);
- try {
- return JSON.parse(value);
- } catch (e) {
- return value;
- }
- }
- // 删除缓存
- function remove(key) {
- const fullKey = STORAGE_PREFIX + key;
- uni.removeStorageSync(fullKey);
- }
- //例子: cacheManager.updateObject('user', { www: undefined }); //删除
- function updateObject(key, updates) {
- let obj = get(key) || {};
- // 合并更新到对象中
- //Object.assign(obj, updates);
- for (let [keyToUpdate, value] of Object.entries(updates)) {
- if (value === null || value === undefined) {
- // 如果值为 null 或 undefined,则删除属性
- delete obj[keyToUpdate];
- } else {
- obj[keyToUpdate] = value;
- }
- }
- set(key, obj);
- }
- function clearAll() {
- const keys = uni.getStorageInfoSync().keys;
- keys.forEach(key => {
- if (key.startsWith(STORAGE_PREFIX)) {
- uni.removeStorageSync(key);
- }
- });
- }
- // 增量修改对象中的数组,支持添加、更新和删除元素
- function updateArrayInObject(key, arrayPath, updateFn) {
- let obj = get(key) || {};
- // 根据arrayPath找到需要修改的数组
- const targetArray = findArrayInObject(obj, arrayPath);
- if (Array.isArray(targetArray)) {
- // 应用更新函数到目标数组上
- updateFn(targetArray);
- // 重新设置缓存
- set(key, obj);
- } else {
- console.error(`${arrayPath}不指向对象中的数组。`);
- }
- }
- // 例子
- // cacheManager.updateArrayInObject('user', 'hobbies', (hobbies) => {
- // hobbies.push('reading');
- // hobbies = 'coding';
- // hobbies.pop();
- // });
- // 在对象中根据路径找到数组
- function findArrayInObject(obj, path) {
- return path.split('.').reduce((acc, curr) => {
- if (acc && acc[curr] !== undefined) {
- return acc[curr];
- } else {
- return undefined;
- }
- }, obj);
- }
- return {
- set,
- get,
- remove,
- updateObject,
- findArrayInObject,
- clearAll
- };
- })();
- export default cacheManager;
|