抱歉,如果这确实很明显,但是我是Vue的新手,可能需要一些帮助。
我正在从商店中抓取一系列数据(帖子),并试图仅对阵列中的一个对象进行日志记录,但是每次都显示未定义。如果我控制台记录整个阵列,它将返回正常。
我猜想这与在创建的hook中的console.log之前没有加载数据有关?我已经尽力了,这让我发疯。任何帮助表示赞赏(下面的简化代码)。
<script>
export default {
components: {},
computed: {
posts() {
return this.$store.state.posts;
}
},
created() {
this.$store.dispatch("getPosts");
console.log(this.posts[0])
},
};
</script>
//Store code Below
export const state = () => ({
posts: [],
})
export const mutations = {
updatePosts: (state, posts) => {
state.posts = posts
}
}
export const actions = {
async getPosts({
state,
commit,
dispatch
}) {
if (state.posts.length) return
try {
let posts = await fetch(
`${siteURL}/wp-json/wp/v2/video`
).then(res => res.json())
posts = posts
.filter(el => el.status === "publish")
.map(({
acf,
id,
slug,
video_embed,
title,
date,
content
}) => ({
acf,
id,
slug,
video_embed,
title,
date,
content
}))
commit("updatePosts", posts)
} catch (err) {
console.log(err)
}
}
}
最佳答案
您会得到一个未定义的信息,因为异步函数尚未填充状态。
对于异步数据,您应该始终使用 setter/getter 。
Vuex Getters
// Store
export const getters = {
get_posts(state) {
return state.posts;
}
}
--
// component
computed: {
posts() {
return this.$store.getters['get_posts'];
}
};