Ideally, you would track the loading
status in vuex so that it's available in all of your components, like your other vuex state.
(理想情况下,您应该在vuex中跟踪loading
状态,以便在所有组件中都可以使用它,就像其他vuex状态一样。)
In your store, create a loading
boolean state.(在您的商店中,创建一个loading
布尔状态。)
Next, create a loading action that will be called in the component like:(接下来,创建将在组件中调用的加载操作,如下所示:)
loadData({ commit, dispatch }) {
commit('SET_LOADING', true);
const loader1 = dispatch('getGenders')
const loader2 = dispatch('getIncomeRanges')
Promise.all([loader1, loader2]).then(() => {
commit('SET_LOADING', false);
})
}
Promise.all
takes an array of promises from your loading actions and will not resolve until all of those promises have resolved.
(Promise.all
会从您的加载操作中获取一系列承诺,并且直到所有这些承诺都解决后才会解决。)
Just make sure that your getGenders
and getIncomeRanges
actions return promises as well.(只要确保您的getGenders
和getIncomeRanges
操作也返回promise。)
Now, in your component, map only loading
and loadData
:(现在,在您的组件中,仅映射loading
和loadData
:)
...mapState('customStore', ['loading']),
...mapActions('customStore', ['loadData'])
Change mounted
to call this action:
(更改mounted
以调用此操作:)
mounted() {
this.loadData()
}
Now you can check loading
anywhere instead of overlay
in all of your components.
(现在,您可以检查任何地方的loading
,而不必overlay
所有组件。)
This is a superior pattern because now loading
is stored only once in vuex with your other state, and is available in all of your components, rather than being managed and passed locally.(这是一种上乘的模式,因为现在loading
仅在vuex中以您的其他状态存储一次,并且在所有组件中都可用,而不是在本地进行管理和传递。)
Here is a demo where I'm simulating AJAX calls with a timeout.
(这是一个演示如何模拟带有超时的AJAX调用的演示 。)
(The example uses a single file to manage vuex + vue so it will look slightly different, but shouldn't be too hard to follow.)((该示例使用单个文件来管理vuex + vue,因此它看起来会稍有不同,但应该不会太难理解。))
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…