| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108 | 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;// 单元测试 引导大鹅提示 缓存Keyexport const SHOW_UNIT_TEST_TISHI = 'SHOW_UNIT_TEST_TISHI';// 单元测试大鹅提示缓存export function useUnitTestTishi() {	return {		updateTishi:() => cacheManager.set(SHOW_UNIT_TEST_TISHI,'has'),		getTishi: () => cacheManager.get(SHOW_UNIT_TEST_TISHI)	}}
 |