/** * globalStorage * sessionStorage * localStorage * * 支持前缀区分 * @module 本地存储 */ const globalData: any = {} const globalStorage = { setItem: (key: string, value: string | null) => globalData[key] = value, getItem: (key: string) => globalData[key], removeItem: (key: string) => Reflect.deleteProperty(globalData, key) } const { localStorage } = window const { sessionStorage } = window export default class Storage { session: any local: any constructor({ prefix = '' } = {}) { this.session = getStorage(prefix, sessionStorage) this.local = getStorage(prefix, localStorage) } } function getStorage(prefix: string, storage: any) { return { /** * 存储数据 * @param {string} key 数据key * @param {*} value 要存储的数据 */ setItem(key: string, value: string | null) { key = prefix + key value = JSON.stringify(value) storage.setItem(key, value) }, /** * 获取数据 * @param {string} key * @return {json} key 对应的数据 */ getItem(key: string) { key = prefix + key let value = storage.getItem(key) if (value === 'undefined') return undefined return JSON.parse(value) }, /** * 删除数据 * @param key */ removeItem(key: string) { key = prefix + key storage.removeItem(key) }, /** * 根据keys获取一组数据 * @param {array} keys * @returns {json} */ multiGet(keys: any) { let values: any = {} keys.forEach((key: string) => values[key] = this.getItem(key)) }, /** * 根据keys 删除一组数据 * @param {array} keys */ multiRemove(keys: any) { keys.forEach((key: string) => this.removeItem(key)) }, /** * 根据prefix清空数据 */ clear() { const localStorageKeys = Object.keys(storage) if (localStorageKeys && localStorageKeys.length) { localStorageKeys.forEach((key: string) => { if (key.startsWith(prefix)) { storage.removeItem(key) } }) } } } }