使用vuex缓存数据并优化自己的vuex-cache
需求:
cache使用map来实现ES6 模块与 CommonJS 模块的差异
因为esm输出的是值的引用,直接就是单例模式了 详细 版本1思路:
注意: 在插件里面获取的mutations-type是包含命名空间的,而在actions里面则是没有命名空间,需要补全。 /mutation-types.js const actions = {
/**
const mutations = { const state = { export default { 编写插件,在这里拦截mutations,判断是否要缓存 /plugin/cache.js {
store.subscribe(({ type,payload },state) => {
// 需要缓存的数据会在mutations-type后面添加CACHED
const needCache = type.split('-').pop() === 'CACHED'
if (needCache) {
// 这里的type会自动加入命名空间所以 cacheKey = type + 把payload格式化成JSON
const cacheKey = type + JSON.stringify(payload && payload.oPayload)
const cacheResponse = cache.get(cacheKey)
// 如果没有缓存就存入缓存
if (!cacheResponse) {
cache.set(cacheKey,payload.response)
}
}
console.log(cache)
})
}
}
const plugin = cachePlugin()
export default plugin
store/index.js Vue.use(Vuex)
const store = new Vuex.Store({ modules: { home,editActivity,editGuide } plugins: [cachePlugin] }) export default store 版本2思路:直接包装fetch函数,在里面里面判断是否需要缓存,缓存是否超时。 优化点:
/actions.js 在fetchOrCache判断是需要缓存,还是请求接口 {
if (cacheTimestemp) {
return ((Date.now() - cacheTimestemp) / 1000) <= diff
} else {
return true
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程之家。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |