如何存放或更新缓存?

缓存数据来源是预知的,我们可以预先定义哪些 mutation 是缓存相关的。

我们期望这个过程更自然一点,通过某种变化自动映射,使以后不管缓存类别增加还是减少都能修改极少的代码来应对变化。

Vuex的插件可以拦截 mutations,借助这个机制,我们可以制定一种策略化的规则。

可以规定,所有需要更新缓存的 mutationType 都要符合这种格式:module-type-cacheKey,非缓存的 mutationType 格式为 module-type。

那么就可以拦截 mutation,去做我们想做的事了:

store.subscribe(({ type, payload }) => {
 const cacheKey = type.split('-')[2]
 if (cacheKey) {
  Cache.save(cacheKey, payload)
 }
})

如何从缓存取数据避免请求?

只需要在缓存相关的 action 中加入缓存判断。

action
fetchData({commit}) {
 const cacheData = Cache.get(cacheKey)
 if(!cacheData) {
  Api.getData().then(data => {
   commit(mutationType, data)
  })
 } else {
  commit(mutationType, cacheData)
 }
}

设计优化

以上的确已经足够完成缓存 读取 --> 更新 的工作了。但试想一下将来某个其他数据类别要做缓存,我们就要把上面的代码格式再搬一遍。

即:把新的需要缓存的数据类别对应的 mutationType 加 cacheKey 后缀,把获取数据的 action 中加缓存判断。

虽然实际编码中也没有多大的工作量,但感觉还不是最好的开发体验。

action优化

action 中的痛点是:每次都需要重复写缓存判断。可以把这个判断过程拿出来放到一个大家都能访问到的公共的地方,且最好是与 Vuex 契合的。

Vuex 支持 action 相互调用,我们可以设置一个单独的 action 用来提交。

commitAction({ commit }, mutationType, getData) {
 const cacheKey = mutationType.split('-')[2]
 const cacheData = Cache.get(cacheKey || '')
 if(!cacheData) {
  getData().then(data => {
   commit(mutationType, data)
  })
 } else {
  commit(mutationType, cacheData)
 }
},
fetchData({ dispatch }) {
 dispatch('commitAction', mutationType, Api.getData)
}

不管是否需要缓存最终都走同一个 action 去提交,由这个 action 去做决策。

mutation优化

mutation 的痛点在于:加后缀啊!加后缀啊!!

如果一个数据的相关逻辑复杂,可能对应很多个 mutationType,每个都需要:加后缀!

要是代码能自动识别需要走缓存的 mutationType 就完美了!

mutationType 默认的格式为 module-type,假如业务中一个 module 对应一个数据类别,我们就可以基于 module 作缓存识别。

cacheConfig.js
export default {
 module1: 'key1',
 module2: 'key2',
 //...
}
action
commitAction({ commit }, mutationType, getData) {
 const module = mutationType.split('-')[0]
 const cacheKey = CacheConfig[module] || ''
 const cacheData = Cache.get(cacheKey)
 if(!cacheData) {
  getData().then(data => {
   commit(mutationType, data)
  })
 } else {
  commit(mutationType, cacheData)
 }
},
fetchData({ dispatch }) {
 dispatch('commitAction', mutationType, Api.getData)
}
interceptor
store.subscribe(({ type, payload }) => {
 const module = type.split('-')[0]
 const cacheKey = CacheConfig[module]
 if (cacheKey) {
  Cache.save(cacheKey, payload)
 }
})

当我们需要新增或减少缓存数据,只需要去 cacheConfig 中增加或减少一项模块配置。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对脚本之家的支持。

点赞(80)

评论列表共有 0 条评论

立即
投稿
返回
顶部