export default { /** * 设置本地存储 同步 * @param {string} key * @param {*} data */ setStorageSync(key, data) { const value = typeof data === 'string' ? data : JSON.stringify(data); uni.setStorageSync(key, value); }, /** * 获取本地存储的信息 根据key * @param {string} key * @return {string} */ getStorageSync(key) { return uni.getStorageSync(key); }, /** * 根据key移除某条数据 同步 * @param {string} key */ removeStorageSync(key) { uni.removeStorageSync(key); }, /** * 清楚全部数据 同步 */ clearStorageSync() { uni.clearStorageSync(); }, /** * 设置本地存储 异步 * @param {string} key * @param {*} data */ setStorage(key, data) { uni.$t.storage.checkCapacity(); return new Promise((resolve, reject) => { const value = typeof data === 'string' ? data : JSON.stringify(data); uni.setStorage({ key, data: value, success() { resolve(`数据${key}存储成功`); }, fail() { reject(`数据${key}存储失败`); }, }); }); }, /** * 获取本地存储的信息 根据key 异步 * @param {string} key * @return {string} */ getStorage(key) { return new Promise((resolve, reject) => { uni.getStorage({ key, success(res) { resolve(res.data); }, fail(error) { reject(`数据${key}获取失败, error: ${error.errMsg}`); }, }); }); }, /** * 根据key移除某条数据 异步 * @param {string} key */ removeStorage(key) { return new Promise((resolve, reject) => { uni.removeStorage({ key, success(res) { resolve(res); }, fail(error) { reject(`数据${key}删除失败, error: ${error}`); }, }); }); }, /** * 清楚全部数据 异步 */ clearStorage() { uni.clearStorage(); }, // 检测local Storage容量 超出容量清空数据缓存 checkCapacity() { /* #ifdef H5 */ const capacity = JSON.stringify(localStorage).length; let max = 1024 * 1024 * 4; if (capacity >= max) { uni.$t.storage.clearStorage(); } /* #endif */ }, };