alipay-emulator/utils/storage.js

57 lines
1.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 本地存储工具类
export const storage = {
// 保存数据
set(key, value) {
try {
const data = typeof value === 'object' ? JSON.stringify(value) : value;
uni.setStorageSync(key, data);
return true;
} catch (error) {
console.error('存储数据失败:', error);
return false;
}
},
// 获取数据
get(key) {
try {
const data = uni.getStorageSync(key);
if (data === null || data === undefined) {
return null;
}
// 尝试解析JSON
try {
return JSON.parse(data);
} catch (e) {
// 如果不是JSON格式直接返回原始数据
return data;
}
} catch (error) {
console.error('获取数据失败:', error);
return null;
}
},
// 删除数据
remove(key) {
try {
uni.removeStorageSync(key);
return true;
} catch (error) {
console.error('删除数据失败:', error);
return false;
}
},
// 清空所有数据
clear() {
try {
uni.clearStorageSync();
return true;
} catch (error) {
console.error('清空数据失败:', error);
return false;
}
}
};