由于小程序需要一个带有过期时间的缓存功能,原生缓存又不支持,于是就自己写了一个
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| import { isType } from './index';
const DEFAULT_TIME_KEY = 'always';
export default class Storage { constructor() { this.timeSign = '|-|'; }
isObj(value) { return isType(value) === 'object'; }
set(key, value, timestamp = DEFAULT_TIME_KEY) { let params;
if (this.isObj(value)) { params = Object.assign(value, { startTime: timestamp }); } else { params = value + this.timeSign + timestamp; }
uni.setStorageSync(key, params); }
get(key) { const value = uni.getStorageSync(key);
if (value) { const arr = value.split(this.timeSign); if (arr.length > 1) { if (new Date().getTime() > arr[1]) { this.remove(key); return null; } return arr[0]; } return arr[0]; }
return null; }
remove(key) { if (!key) throw new Error('key为必填项'); uni.removeStorageSync(key); }
clear() { uni.clearStorageSync(); } }
|
main.js
注册到全局
1
| Vue.prototype.$storage = new Storage();
|
使用:
1 2 3
| this.$storage.set('key', 123); this.$storage.get('key'); this.$storage.remove('key');
|