如何在NUXT中使用异步操作实现非阻滞剂中间件
我想用API的数据初始化我的商店。 NuxtServerinit对我的情况并不有用,因为我的NUXT应用程序目标设置为'static'。 我正在尝试实现路由器中间件,以异步获取数据,但没有阻止主线程。换句话说,中间件可以使页面加载(已安装),但是每当获取数据时,更新会存储。
异步中间件的问题是,在获取数据之前,它将无法解决。
,同步中间件的问题是,我的商店不会更新。
这是我的实现:
中间件/initializer.js
export default function({ store }) {
store.dispatch('app/initializeApp').then(() => console.log('app initialized'))
}
store/app.js
initializeApp({ dispatch }) {
return dispatch('fetchOptions')
},
fetchOptions({ commit }) {
return this.$axios.$post(someEndpoint).then(({ options }) => {
commit('setAppOptions', options)
return true
}).catch(() => false)
}
我不明白控制台日志为什么有效,但我的商店未更新。
I want to initialize my store with data from an API.
nuxtServerInit is not useful for my case because my Nuxt app target is set on 'static'.
I'm trying to implement a router middleware to fetch data asynchronously but without blocking the main thread. In other word, the middleware lets the page to load (mounted) but updates store whenever the data has been fetched.
The problem with an asynchronous middleware is that, it will not resolved until data is fetched.
And, the problem with a synchronous middleware is that, my store will not updated.
here is my implementation:
middleware/initializer.js
export default function({ store }) {
store.dispatch('app/initializeApp').then(() => console.log('app initialized'))
}
store/app.js
initializeApp({ dispatch }) {
return dispatch('fetchOptions')
},
fetchOptions({ commit }) {
return this.$axios.$post(someEndpoint).then(({ options }) => {
commit('setAppOptions', options)
return true
}).catch(() => false)
}
I don't understand why the console log works but my store is not updated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论