session存储及使用封装

export default { isUseClientCache: true, DB_NAME: 'sinime', isAvailable: function () { let isSessionStorageAvailable = ('sessionStorage' in window) && window['sessionStorage'] !== null && window['sessionStorage'] !== undefined return this.isUseClientCache && isSessionStorageAvailable }, get: function (key) { if (!this.isAvailable() || key == null) { return } let json, obj, cacheKey cacheKey = this.DB_NAME + key json = window.sessionStorage.getItem(cacheKey) /* eslint-disable no-eval */ obj = eval('(' + json + ')') return (obj == null ? null : obj.value) }, contain: function (key) { if (!this.isAvailable() || key == null) { return } let json, obj, cacheKey cacheKey = this.DB_NAME + key json = window.sessionStorage.getItem(cacheKey) /* eslint-disable no-eval */ obj = eval('(' + json + ')') /* eslint-disable no-unneeded-ternary */ return (obj == null ? false : true) }, put: function (key, value, timestamp) { if (!this.isAvailable()) { return } let cacheKey let cacheValue = {} cacheValue.value = value cacheValue.timestamp = timestamp || 1 cacheKey = this.DB_NAME + key let values = JSON.stringify(cacheValue) window.sessionStorage.setItem(cacheKey, values) }, remove: function (key) { let cacheKey = this.DB_NAME + key window.sessionStorage.removeItem(cacheKey) }, clear: function () { if (!this.isAvailable()) { return } let key for (let i = 0; i < window.sessionStorage.length; i++) { key = window.sessionStorage.key(i) if (key.indexOf(this.DB_NAME) > -1) { window.sessionStorage.removeItem(key) } } }, putMultiple: function (keys, values, timestamps) { }, getKeys: function () { if (!this.isAvailable()) { return } let key let keys = [] for (let i = 0; i < window.sessionStorage.length; i++) { key = window.sessionStorage.key(i) if (key.indexOf(this.DB_NAME > -1)) { key = key.substring(this.DB_NAME.length) keys.push(key) } } return keys }, getCount: function () { if (!this.isAvailable()) { return } let key let count = 0 for (let i = 0; i < window.sessionStorage.length; i++) { key = window.sessionStorage.key(i) if (key.indexOf(this.DB_NAME) > -1) { count++ } } return count } }

随机浏览