我是Vuex的新手,并且一直在尝试使用Nuxt学习Vuex库,并且一直在努力寻找当前提及Vuex的模块方法同时还使用Nuxt的所有教程。
无论如何,我一直在遵循一门课程,但现在我意识到这已经过时了并且陷入了困境。
我在index.js
下创建了一个/store
文件,如下所示:
export const state = () => ({
})
export const mutations = ({
})
export const actions = ({
})
export const getters = ({
})
使用模块化方法,我还在posts.js
下添加了/store
文件。我的posts.js
文件如下所示:
export const state = () => ({
loadedPosts: []
})
export const mutations = ({
setPosts(state, posts) {
state.loadedPosts = posts
}
})
export const actions = ({
setPosts(vuexContext, posts) {
vuexContext.commit('setPosts', posts);
}
})
export const getters = ({
loadedPosts(state) {
return state.loadedPosts
}
})
最后,我试图在我的/posts/index.vue
页面中从Vuex调用我的帖子获取者,就像这样:
<template>
<div class="posts-page">
<PostList :posts="loadedPosts"/>
</div>
</template>
<script>
import PostList from '@/components/Posts/PostList'
export default {
components: {
PostList
},
// data() {
// return {
// loadedPosts: [
// { id: '1', title: 'First Post', previewText: 'So it has come to my attention recen...', thumbnail: 'https://source.unsplash.com/featured/?tech' },
// { id: '2', title: 'Second Post', previewText: 'Until recently I has assumed that it w...', thumbnail: 'https://source.unsplash.com/featured/?tech' },
// ]
// }
// },
// created() {
// this.$store.dispatch('posts/setPosts', this.loadedPosts)
// }
fetch(context) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve({
loadedPosts: [
{
id: '1',
title: 'First Post',
previewText: 'Today I learned that patience is very important',
thumbnail: 'https://source.unsplash.com/featured/?tech'
},
{
id: '2',
title: 'Second Post',
previewText: 'Still being patient. Woo!',
thumbnail: 'https://source.unsplash.com/featured/?tech'
},
]
});
}, 2000);
})
.then(data => {
context.store.commit('posts/setPost', data.loadedPosts)
})
.catch(e => {
context.error(new Error());
})
},
computed: {
loadedPosts() {
return this.$store.getters.loadedPosts
}
}
}
</script>
我不确定要解决此错误该怎么做。我认为并希望这是一个新手错误。
完整的仓库可以在这里轻松克隆或查看: https://github.com/SIeep/personal-til-app
我的计算loadedPosts()
方法显示它正在Vue开发工具的Vuex部分返回一个未定义的对象。只是不确定我应该怎么做才能解决此问题。
谢谢您的帮助!