概述
实际项目开发当中,离不开操作本地存储,包括localstorage,sessionstorage,cookie,本文主要封装这三个的存取对外暴露一样的方法,方便项目的使用。本文中的cookie操作用到的插件为vue-cookies。
代码
import VueCookies from 'vue-cookies';
const LOCALSTORAGE = 'localStorage';
const SESSIONSTORAGE = 'sessionStorage';
const COOKIES = 'cookies';
const mapCache = {
[LOCALSTORAGE]: localStorage,
[SESSIONSTORAGE]: sessionStorage,
[COOKIES]: VueCookies,
};
class Cache {
constructor() {
this.storageTypeMap = new Map(); //对应cache映射表
this.storageArray = [LOCALSTORAGE, SESSIONSTORAGE, COOKIES]; //cache字段名
this.setStorageTypeMap(); //设置映射关系
}
// 存
setItem(storageType, key, value, expireTimes, path) {
let setItem = this.storageTypeMap.get(storageType).setItem();
setItem.call(mapCache[storageType], key, JSON.stringify(value), expireTimes, path);
}
// 移除
removeItem(storageType, key, value) {
let removeItem = this.storageTypeMap.get(storageType).removeItem();
removeItem.call(mapCache[storageType], key, value);
}
// 获取
getItem(storageType, key) {
let getItem = this.storageTypeMap.get(storageType).getItem();
let getItemResultBack = getItem.call(mapCache[storageType], key); //最终根据返回值决定是否序列号
return getItemResultBack && storageType == COOKIES
? typeof getItemResultBack != 'object'
? JSON.parse(getItemResultBack)
: getItemResultBack
: JSON.parse(getItemResultBack);
}
// 清空
clear() {
if (storageType == COOKIES) return;
let clear = this.storageTypeMap.get(storageType).clear();
clear.call(mapCache[storageType], key, value);
}
// 根据存储类型设置cache中api的映射关系
setStorageTypeMap() {
this.storageArray.forEach(cache => {
this.storageTypeMap.set(cache, {
getItem() {
return cache == COOKIES
? VueCookies.get
: cache == LOCALSTORAGE
? localStorage.getItem
: sessionStorage.getItem;
},
setItem() {
return cache == COOKIES
? VueCookies.set
: cache == LOCALSTORAGE
? localStorage.setItem
: sessionStorage.setItem;
},
removeItem() {
return cache == COOKIES
? VueCookies.remove
: cache == LOCALSTORAGE
? localStorage.removeItem
: sessionStorage.removeItem;
},
clear() {
return cache == COOKIES ? undefined : cache == LOCALSTORAGE ? localStorage.getItem : sessionStorage.getItem;
},
});
});
}
static getCacheInstance() {
if (Cache.instance) {
return Cache.instance;
}
return new Cache();
}
}
export default new Cache();