【发布时间】:2020-07-15 13:56:05
【问题描述】:
很抱歉,如果这真的很明显,但我是 Vue 新手,需要一些帮助。
我正在从我的存储中获取一组数据(帖子)并尝试控制台记录数组中的一个对象,但它每次都显示未定义。如果我控制台记录整个数组,它会返回正常。
我猜这与 created 钩子中的 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)
}
}
}
【问题讨论】:
标签: arrays vue.js object vuex nuxt.js