const DEFAULT_EFFECTIVE_TIME = 90 * 24 * 60 * 60 * 1000 /** * @description: 缓存到localStorage下,有效期默认3个月,可自定义 * @param {String} 缓存数据对应的Key * @param {data} 缓存数据对应的Value * @param {milliseconds} 数据获取有效期,毫秒级 * @return: undefined */ export function save (key, val, time) { if (Object.prototype.toString.call(val) !== '[object Undefined]') { let curTime = new Date().getTime() let effectiveTime = curTime + (time || DEFAULT_EFFECTIVE_TIME) window.localStorage.setItem(key, JSON.stringify({ data: val, time: effectiveTime })) } } /** * @description: 获取缓存到localStorage下的数据 * @param {String} 缓存数据对应的Key * @return: 对应的Key的Value数据 */ export function get (key) { try { let data = window.localStorage.getItem(key) if (data) { let dataObj = JSON.parse(data) if (dataObj.time - new Date().getTime() < 0) { remove(key) return '' } else { return dataObj.data } } else { return '' } } catch (e) { return '' } } /** * @description: 删除缓存到localStorage下的数据 * @param {String} 缓存数据对应的Key * @return: undefined */ export function remove (key) { window.localStorage.removeItem(key) } /** * @description: 缓存到sessionStorage下 * @param {String} 缓存数据对应的Key * @param {data} 缓存数据对应的Value * @return: undefined */ export function sessionSave (key, val) { if (Object.prototype.toString.call(val) !== '[object Undefined]') { window.sessionStorage.setItem(key, JSON.stringify(val)) } } /** * @description: 获取缓存到sessionStorage下的数据 * @param {String} 缓存数据对应的Key * @return: 对应的Key的Value数据 */ export function sessionGet (key) { try { let data = window.sessionStorage.getItem(key) if (data) { return JSON.parse(data) } else { return '' } } catch (e) { return '' } } /** * @description: 删除缓存到sessionStorage下的数据 * @param {String} 缓存数据对应的Key * @return: undefined */ export function sessionRemove (key) { window.sessionStorage.removeItem(key) }