我们在项目中通常会对缓存进行一些操作,为了便于全局调用,会对缓存的设置、获取及删除方法进行封装成一个工具类。
首先我们在src目录下创建一个plugins文件夹,在plugins下创建cache文件夹并创建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);},//对象或者数组的存取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);},// 检测缓存是否存在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);},// 检测缓存是否存在has(key){return localStorage.getItem(key) ? true:false;},setItem(params){let obj = {name:'',value:'',expires:"",startTime:new Date().getTime()}let options = {};//将obj和传进来的params合并Object.assign(options,obj,params);if(options.expires){//如果options.expires设置了的话//以options.name为key,options为值放进去localStorage.setItem(options.name,JSON.stringify(options));}else{//如果options.expires没有设置,就判断一下value的类型let type = Object.prototype.toString.call(options.value);//如果value是对象或者数组对象的类型,就先用JSON.stringify转一下,再存进去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 {/*** 会话级缓存*/session: sessionCache,/*** 本地缓存*/local: localCache};
复制代码
Copy
挂载到vue原型上全局使用
import cache from '@/plugins/cache/index'
Vue.prototype.$cache = cache
复制代码
Copy
使用方法
// localstroge的缓存
this.$cache.local.has(key) //判断有没有缓存
this.$cache.local.setJSON(key,value); //存储
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');
Copy