【发布时间】:2018-07-01 08:34:20
【问题描述】:
有两个页面(或相对于 vue 术语的组件)都需要相同的数据集,这些数据是通过 http 上的 api 提供的。访问这两个组件的顺序是未定义的(或者,取决于用户行为),并且数据应该只获取一次,因为它不会发生很大变化。
我知道state 存储实际数据的想法,mutations 对state 进行变异,actions 将脏工作作为异步请求、多变异协调等。
问题是:执行上述某些缓存逻辑的最佳做法是什么?
我想出了以下三种方法,但它们都不适合我:
缺点:
-
我需要在到处访问数据之前调度操作,因为我不知道数据是否已经被获取。
// ComponentA async mouted () { await this.store.dispatch('fetchData') this.someData = this.store.state.someData } // ComponentB async mouted () { await this.store.dispatch('fetchData') this.someData = this.store.state.someData } // vuex action { async fetchData ({ state, commit }) { // handles the cache logic here if (state.someData) return commit('setData', await apis.fetchData()) } } -
缓存逻辑分散在整个代码库中——臭~
// ComponentA async mouted () { if (this.store.state.someData === undefined) { // handles the cache logic await this.store.dispatch('fetchData') } this.someData = this.store.state.someData } // ComponentB async mouted () { if (this.store.state.someData === undefined) { // handles the cache logic await this.store.dispatch('fetchData') } this.someData = this.store.state.someData } // vuex action { async fetchData ({ state, commit }) { commit('setData', await apis.fetchData()) } } -
可能是这三个中最完美的一个,但是我觉得使用动作调度的返回值作为数据有点奇怪。随着商店的增长,缓存逻辑将分散在所有动作中(将会有越来越多的动作重复相同的缓存逻辑)
// ComponentA async mouted () { this.someData = await this.store.dispatch('fetchData') } // ComponentB async mouted () { this.someData = await this.store.dispatch('fetchData') } // vuex action { async fetchData ({ state, commit }) { if (!state.someData) commit('setData', await apis.fetchData()) return state.someData } }
我更喜欢将缓存逻辑放入我的“vue&vuex-independent”网络层。但随后网络层的“缓存”部分可能会变成另一个“vuex”存储。呵呵
【问题讨论】: