我們?cè)陧?xiàng)目中通常會(huì)對(duì)緩存進(jìn)行一些操作,為了便于全局調(diào)用,會(huì)對(duì)緩存的設(shè)置、獲取及刪除方法進(jìn)行封裝成一個(gè)工具類(lèi)。
首先我們?cè)趕rc目錄下創(chuàng)建一個(gè)plugins文件夾,在plugins下創(chuàng)建cache文件夾并創(chuàng)建index.js,代碼如下:
const sessionCache = {
set(key, value) {
if (!sessionStorage) {
return;
}
if (key != null && value != null) {
sessionStorage.setItem(key, value);
}
},
get(key) {
if (!sessionStorage) {
return null;
}
if (key == null) {
return null;
}
return sessionStorage.getItem(key);
},
//對(duì)象或者數(shù)組的存取
setJSON(key, jsonValue) {
if (jsonValue != null) {
this.set(key, JSON.stringify(jsonValue));
}
},
getJSON(key) {
const value = this.get(key);
if (value != null) {
return JSON.parse(value);
}
},
remove(key) {
sessionStorage.removeItem(key);
},
// 檢測(cè)緩存是否存在
has(key)
{
return sessionStorage.getItem(key) ? true:false;
},
};
const localCache = {
set(key, value) {
if (!localStorage) {
return;
}
if (key != null && value != null) {
localStorage.setItem(key, value);
}
},
get(key) {
if (!localStorage) {
return null;
}
if (key == null) {
return null;
}
return localStorage.getItem(key);
},
setJSON(key, jsonValue) {
if (jsonValue != null) {
this.set(key, JSON.stringify(jsonValue));
}
},
getJSON(key) {
const value = this.get(key);
if (value != null) {
return JSON.parse(value);
}
},
remove(key) {
localStorage.removeItem(key);
},
// 檢測(cè)緩存是否存在
has(key)
{
return localStorage.getItem(key) ? true:false;
},
setItem(params){
let obj = {
name:'',
value:'',
expires:"",
startTime:new Date().getTime()
}
let options = {};
//將obj和傳進(jìn)來(lái)的params合并
Object.assign(options,obj,params);
if(options.expires){
//如果options.expires設(shè)置了的話
//以options.name為key,options為值放進(jìn)去
localStorage.setItem(options.name,JSON.stringify(options));
}else{
//如果options.expires沒(méi)有設(shè)置,就判斷一下value的類(lèi)型
let type = Object.prototype.toString.call(options.value);
//如果value是對(duì)象或者數(shù)組對(duì)象的類(lèi)型,就先用JSON.stringify轉(zhuǎn)一下,再存進(jìn)去
if(Object.prototype.toString.call(options.value) == '[object Object]'){
options.value = JSON.stringify(options.value);
}
if(Object.prototype.toString.call(options.value) == '[object Array]'){
options.value = JSON.stringify(options.value);
}
localStorage.setItem(options.name,options.value);
}
}
};
export default {
/**
* 會(huì)話級(jí)緩存
*/
session: sessionCache,
/**
* 本地緩存
*/
local: localCache
};
復(fù)制代碼
掛載到vue原型上全局使用
import cache from '@/plugins/cache/index'
Vue.prototype.$cache = cache
復(fù)制代碼
使用方法
// localstroge的緩存
this.$cache.local.has(key) //判斷有沒(méi)有緩存
this.$cache.local.setJSON(key,value); //存儲(chǔ)
let key = this.$cache.local.getJSON('key'); //獲取
// sessionStorage
this.$cache.session.has(key)
this.$cache.session.setJSON( key,value);
let key = this.$cache.session.getJSON('key');