将数据存储在localStorage中,封装一个Storage类——NBStorage,通过在key前设置前缀的方式来区分NBStorage存入的数据和其他方式存入的数据。
class NBStorage {
constructor() {
// 需要存入的数据的前缀
this.PREFIX = 'NBS_';
// 记录数据过期时间的前缀
this.EXPIRES_PREFIX = this.PREFIX + 'EXPIRES_'
// 初始化时清理过期数据
this._checkAll();
}
// 遍历所有带前缀的数据
_checkAll() {
// localStorage可以当做一个对象直接用for...in 遍历,学到了
for (let k in localStorage) {
// 使用string.includes('str')的方法判断string中是否包含'str'字段
if (k.includes(this.EXPIRES_PREFIX)) {
this._checkItem(k.replace(this.EXPIRES_PREFIX, ''));
}
}
}
_checkItem(key) {
// 参数的key为用户输入的key值,直接在localStorage里是检索不到的,需要加前缀
const targetKey = this._getTargetKey(key);
const expiresKey = this._getExpiresKey(key);
// 在localStorage检索加前缀后的key值
const expires = localStorage.getItem(expiresKey);
const now = Date.now()
// 检测是否过期,删除过期数据以及其expires
if (now > +expires) {
localStorage.removeItem(targetKey)
localStorage.removeItem(expiresKey)
}
}
// 给存入数据key加前缀
_getTargetKey(key) {
return this.PREFIX + key
}
// 给存入过期时间key加前缀
_getExpiresKey(key) {
return this.EXPIRES_PREFIX + key
}
getItem(key) {
// 清理过期数据是在初始化以及获取数据时进行的,只要保证用户获取不到过期数据即可
this._checkItem(key)
const targetKey = this._getTargetKey(key);
// 检索数据
return localStorage.getItem(targetKey);
}
setItem(key, value, expires = 0) {
const targetKey = this._getTargetKey(key);
const expiresKey = this._getExpiresKey(key);
localStorage.setItem(targetKey, value)
// 添加过期时间
localStorage.setItem(expiresKey, Date.now() + expires + '');
}
removeItem(key) {
const targetKey = this._getTargetKey(key);
const expiresKey = this._getExpiresKey(key);
localStorage.removeItem(targetKey)
localStorage.removeItem(expiresKey);
}
// clear不能直接调用localStorage的clear,只需要清理带有前缀的数据,因此直接遍历,一个一个清除
clear() {
for (let k in localStorage) {
if (k.includes(this.PREFIX) || k.includes(this.EXPIRES_PREFIX)) {
localStorage.removeItem(k)
}
}
}
}
export default NBStorage