function Cache() { try { this.data = JSON.parse(sessionStorage.getItem('cached-data')) || [] } catch (error) { this.data = [] } } /** * 向缓存中塞值 * @param key 字段key * @param value 字段值 */ Cache.prototype.set = function(key, value) { // 如果值不存在 if (!value) { this.data.push(key) } // 将键值对的值保存 this.data[key] = value // 将数据保存到storage中 sessionStorage.setItem(`cached-data`, JSON.stringify(this.data)) } /** * 从缓存中获取值 * @param key 字段key * @param defaultKey 没取到值的默认值 */ Cache.prototype.get = function(key, defaultValue) { return this.data[key] || defaultValue } /** * 从缓存中移除值 * @param key 字段key */ Cache.prototype.remove = function(key) { // 删除值 delete this.data[key] // 将数据保存到storage中 sessionStorage.setItem(`cached-data`, JSON.stringify(this.data)) } export default new Cache()