vue.js - Nuxt 等待异步 + vuex
问题描述
我正在使用 nuxt 和 vuex。在 vuex 中获取数据:
actions: {
get_posts(ctx) {
axios.get("http://vengdef.com/wp-json/wp/v2/posts").then(post => {
let posts = post.data;
if (!posts.length) return;
let medias_list = "";
posts.forEach(md => {
medias_list += md.featured_media + ","
});
medias_list = medias_list.slice(0, -1);
let author_list = "";
posts.forEach(md => {
author_list += md.author + ","
});
author_list = author_list.slice(0, -1);
axios.all([
axios.get("http://vengdef.com/wp-json/wp/v2/media?include=" + medias_list),
axios.get("http://vengdef.com/wp-json/wp/v2/users?include=" + author_list),
axios.get("http://vengdef.com/wp-json/wp/v2/categories"),
]).then(axios.spread((medias, authors, categories) => {
ctx.commit("set_postlist", {medias, authors, categories} );
})).catch((err) => {
console.log(err)
});
})
}
},
在 vuex 状态下,我有来自下面的 exaple 的动态后列表。我如何在 Nuxt 中使用它?
在 nuxt 我知道 async fetch 和 asyncData。
async fetch () {
this.$store.dispatch("posts/get_posts");
}
那是行不通的。
在 vuex 操作加载所有数据之前,我怎么能对 nuxt 说,等待加载页面?
解决方案
正如您已经提到的,有:
- 取钩
- 异步数据
并且在这里很好地描述了差异
您的代码不起作用的原因可能在于您的商店操作。它应该返回一个承诺,尝试return
在 axios get 方法之前添加 ->
get_posts(ctx) {
return axios.get(...
// ...
然后,在您的页面上:
async fetch () {
await this.$store.dispatch("posts/get_posts");
}
此外,在上面的评论中,您说您不想在存储中提交数据:
...仅在 vuex 之后加载页面,我不需要在 vuex 中传递数据
但是你用这条线来做:
ctx.commit("set_postlist", {medias, authors, categories} );
如果您不想将数据保存在存储中,只需将上面的行替换为:
return Promise.resolve({ medias, authors, categories })
并在您的页面上获取它:
async fetch () {
this.posts = await this.$store.dispatch("posts/get_posts");
// now you can use posts in template
}