使用vuex缓存数据并优化自己的vuex-cache

2020-06-14 05:56:37易采站长站整理

需求:

请求接口之后,缓存当前接口的数据,下次请求同一接口时拿缓存数据,不再重新请求
添加缓存失效时间

cache使用map来实现

ES6 模块与 CommonJS 模块的差异

CommonJS 模块输出的是一个值的拷贝,ES6 模块输出的是值的引用。
CommonJS 模块是运行时加载,ES6 模块是编译时输出接口。

因为esm输出的是值的引用,直接就是单例模式了

详细


export let cache = new Cache()

版本1

思路:

在vuex注册插件,插件会在每次mutations提交之后,判断要不要写入cache
在提交actions的时候判断是否有cache,有就拿cache里面的数据,然后把数据commit给mutataios

注意: 在插件里面获取的mutations-type是包含命名空间的,而在actions里面则是没有命名空间,需要补全。

/mutation-types.js


/**
* 需要缓存的数据会在mutations-type后面添加-CACHED
*/
export const SET_HOME_INDEX = 'SET_HOME_INDEX-CACHED'
/modules/home/index.js

const actions = {
/**
* @description 如果有缓存,就返回把缓存的数据,传入mutations,
* 没有缓存就从接口拿数据,存入缓存,把数据传入mutations
*/
async fetchAction ({commit}, {mutationType, fetchData, oPayload}) {
// vuex开启了命名空间,所这里从cachekey要把命名空间前缀 + type + 把payload格式化成JSON
const cacheKey = NAMESPACE + mutationType + JSON.stringify(oPayload)
const cacheResponse = cache.get(cacheKey || '')
if (!cacheResponse) {
const [err, response] = await fetchData()
if (err) {
console.error(err, 'error in fetchAction')
return false
}
commit(mutationType, {response: response, oPayload})
} else {
console.log('已经进入缓存取数据!!!')
commit(mutationType, {response: cacheResponse, oPayload})
}
},
loadHomeData ({ dispatch, commit }) {
dispatch(
'fetchAction',
{
mutationType: SET_HOME_INDEX,
fetchData: api.index,
}
)
}
}

const mutations = {
[SET_HOME_INDEX] (state, {response, oPayload}) {},
}

const state = {
indexData: {}
}

export default {
namespaced: NAMESPACED,
actions,
state,
getters,
mutations
}

编写插件,在这里拦截mutations,判断是否要缓存
/plugin/cache.js


import cache from 'src/store/util/CacheOfStore'
// import {strOfPayloadQuery} from 'src/store/util/index'
/**
* 在每次mutations提交之后,把mutations-type后面有CACHED标志的数据存入缓存,
* 现在key值是mutations-type