123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102 |
- /**
- * 缓存数据优化
- * const storage = require('@/utils/storage');
- * import storage from '@/utils/storage'
- * 使用方法 【
- * 一、设置缓存
- * string storage.setKey('k', 'string你好啊');
- * json storage.setKey('k', { "b": "3" }, 2);
- * array storage.setKey('k', [1, 2, 3]);
- * boolean storage.setKey('k', true);
- * 二、读取缓存
- * 默认值 storage.getKey('k')
- * string storage.getKey('k', '你好')
- * json storage.getKey('k', { "a": "1" })
- * 三、移除/清理
- * 移除: storage.remove('k');
- * 清理:storage.clear();
- * 】
- * @type {String}
- */
- import {inArray} from "@/utils/util";
- const postfix = '_expiry' // 缓存有效期后缀
- /**
- * @param {function}
- */
- class Storage {
- /**
- * 设置缓存
- * @param {string} k [键名]
- * @param {*} v [键值]
- * @param {string|number|null} t [时间、单位秒]
- */
- static setKey(k, v, t = null) {
- uni.setStorageSync(k, v)
- const seconds = parseInt(t)
- if (seconds > 0) {
- let timestamp = Date.parse(new Date())
- timestamp = timestamp / 1000 + seconds
- uni.setStorageSync(k + postfix, timestamp + '')
- } else {
- uni.removeStorageSync(k + postfix)
- }
- }
- /**
- * 获取缓存
- * @param {string} k [键名]
- * @param {*} def [获取为空时默认]
- */
- static getKey(k, def = false) {
- const deadTime = parseInt(uni.getStorageSync(k + postfix))
- if (deadTime) {
- if (parseInt(deadTime) < Date.parse(new Date()) / 1000) {
- if (def) {
- return def
- } else {
- return false
- }
- }
- }
- const res = uni.getStorageSync(k)
- if (res) {
- return res
- }
- if (def == undefined || def == "") {
- def = false
- }
- return def
- }
- /**
- * 删除指定缓存
- * @param {Object} k
- */
- static remove(k) {
- uni.removeStorageSync(k)
- uni.removeStorageSync(k + postfix)
- }
- /**
- * 清理所有缓存
- * @return {[type]} [description]
- */
- static clear() {
- uni.clearStorageSync()
- }
- static clearOtherKey(key = []) {
- const res = uni.getStorageInfoSync();
- res.keys.forEach((it) => {
- if (!inArray(it, key)) {
- this.remove(it)
- }
- })
- }
- }
- export default Storage
|