Vuex和前端缓存的整合策略详解
如何存放或更新缓存?
缓存数据来源是预知的,我们可以预先定义哪些mutation是缓存相关的。
我们期望这个过程更自然一点,通过某种变化自动映射,使以后不管缓存类别增加还是减少都能修改极少的代码来应对变化。
Vuex的插件可以拦截mutations,借助这个机制,我们可以制定一种策略化的规则。
可以规定,所有需要更新缓存的mutationType都要符合这种格式:module-type-cacheKey,非缓存的mutationType格式为module-type。
那么就可以拦截mutation,去做我们想做的事了:
store.subscribe(({type,payload})=>{ constcacheKey=type.split('-')[2] if(cacheKey){ Cache.save(cacheKey,payload) } })
如何从缓存取数据避免请求?
只需要在缓存相关的action中加入缓存判断。
action fetchData({commit}){ constcacheData=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){ constcacheKey=mutationType.split('-')[2] constcacheData=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 exportdefault{ module1:'key1', module2:'key2', //... }
action commitAction({commit},mutationType,getData){ constmodule=mutationType.split('-')[0] constcacheKey=CacheConfig[module]||'' constcacheData=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})=>{ constmodule=type.split('-')[0] constcacheKey=CacheConfig[module] if(cacheKey){ Cache.save(cacheKey,payload) } })
当我们需要新增或减少缓存数据,只需要去cacheConfig中增加或减少一项模块配置。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对毛票票的支持。