/** * LocalStorage - 混合App模式,本地存储同步工具 * 用于区分不同开发环境读取不同数据 * @author Tevin */ import Taro from '@tarojs/taro'; export class LocalStorage { constructor() { this._data = { prefixType: '', }; } // 初始化 initial(prefixType) { this._data.prefixType = prefixType; } load(key) { const name = 'AiSim.' + this._data.prefixType + '@' + key; return JSON.parse(Taro.getStorageSync(name) || '{}'); } save(key, value) { if (typeof value !== 'object') { throw new Error('LocalStorage save 方法,value 只接收 Object !'); } const name = 'AiSim.' + this._data.prefixType + '@' + key; Taro.setStorageSync(name, JSON.stringify(value || {})); } remove(key) { const name = 'AiSim.' + this._data.prefixType + '@' + key; Taro.removeStorageSync(name); } getKeys() { const info = Taro.getStorageInfoSync(); const keys = []; const prefix = 'AiSim.' + this._data.prefixType + '@'; info.keys.forEach(storageKey => { if (storageKey.indexOf(prefix) === 0) { const keyName = storageKey.split('@')[1]; keys.push(keyName); } }); return keys; } searchKey(key) { const matches = []; this.getKeys().forEach(keyName => { if (keyName.indexOf(key) >= 0) { matches.push(keyName); } }); return matches; } } export const $localStorage = new LocalStorage();