我正在使用默认的nuxt加载栏,它在简单页面上也能很好地工作。但是,当我使用多个axios请求时,每次发送请求时都会加载进度条。我希望进度条将所有这些请求理解为单个页面加载。我使用了Promise.all,它确实可行。但是我的问题是我正在使用异步vuex调度方法。
所以我的代码是这样的,三个不同的异步分派和进度条加载了三次。我如何做到这一点,使其仅加载一次。谢谢
async fetch({ store }) {
await store.dispatch('LOAD_DATA_1')
await store.dispatch('LOAD_DATA_2')
await store.dispatch('LOAD_DATA_3')
}
它要加载三个不同的时间,因为您的请求是依次进行的,一个接一个,而不是一次完成。要解决此问题,您可以手动启动/停止加载程序。
首先,您要防止nuxt axios插件触发加载栏。参见here。
this.$axios.$get('URL', { progress: false })
然后,您可以在请求完成之前/之后以编程方式手动启动和停止加载栏。
this.$nuxt.$loading.start()
this.$nuxt.$loading.stop()
完整示例:
async fetch({ store }) {
this.$nuxt.$loading.start()
await store.dispatch('LOAD_DATA_1')
await store.dispatch('LOAD_DATA_2')
await store.dispatch('LOAD_DATA_3')
this.$nuxt.$loading.stop()
}
编辑1(请参阅评论):
要在asyncData / fetch中使用,您可以使用以下内容。我不确定您是否应该访问像这样的组件,但是我看不到在上下文中访问$ loading模块的另一种方法...
async fetch(ctx) {
// access the loading component via the access context
ctx.app.components.NuxtLoading.methods.start()
// example, wait 3 seconds before disabling loader
await new Promise(resolve => setTimeout(resolve, 3000))
ctx.app.components.NuxtLoading.methods.finish()
},