当我使用v-for循环遍历div上的“ allPosts”数据时,出现错误。
Nuxt文档说“模块:商店目录中的每个.js文件都转换为命名空间模块”。也许我在这方面缺少什么?
pages / index.vue
<template>
<section id="postgrid">
<div v-for="post in allPosts" :key="post.id"></div>
</section>
</template>
<script>
import {mapGetters} from 'vuex'
import PostTile from '@/components/Blog/PostTile'
export default {
components: {
PostTile
},
computed: mapGetters(['allPosts'])
}
</script>
store / index.js
import Vue from 'vue'
import Vuex from 'vuex'
import Posts from './posts'
const store = new Vuex.Store({
modules: {
Posts
}
})
store / posts.js
const state = () => ({
posts: [
{
id: 0,
title: 'A new beginning',
previewText: 'This will be awesome don\'t miss it',
category: 'Food',
featured_image: 'http://getwallpapers.com/wallpaper/full/6/9/8/668959.jpg',
slug: 'a-new-beginning',
post_body: '<p>Post body here</p>',
next_post_slug: 'a-second-beginning'
},
{
id: 1,
title: 'A second beginning',
previewText: 'This will be awesome don\'t miss it',
category: 'Venues',
featured_image: 'https://images.wallpaperscraft.com/image/beautiful_scenery_mountains_lake_nature_93318_1920x1080.jpg',
slug: 'a-second-beginning',
post_body: '<p>Post body here</p>',
prev_post_slug: 'a-new-beginning',
next_post_slug: 'a-third-beginning'
},
{
id: 2,
title: 'A third beginning',
previewText: 'This will be awesome don\'t miss it',
category: 'Experiences',
featured_image: 'http://eskipaper.com/images/beautiful-reflective-wallpaper-1.jpg',
slug: 'a-third-beginning',
post_body: '<p>Post body here</p>',
prev_post_slug: 'a-second-beginning',
next_post_slug: 'a-forth-beginning'
}
]
})
const getters = {
allPosts: (state) => state.posts
}
export default {
state,
getters
}
答案 0 :(得分:2)
在如何设置和访问商店方面存在许多问题。首先,您使用docs告诉我们的“经典模式”创建商店:
此功能已弃用,并将在Nuxt 3中删除。
因此,为了使用最新的方法,store / index.js应该如下所示:
//store/index.js
//end
这不是一个错误,您实际上不需要任何东西,只要它存在就可以。无需导入vue或vuex或任何模块。
您的store / posts.js基本上可以保持原样,只需更改状态,变异,获取器和要导出常量的操作并删除底部的导出即可:
//store/posts.js
export const state = () => ({
posts: [
...
]
})
export const mutations: {
}
export const actions: {
}
export const getters: {
allPosts: state => state.posts
}
//delete the following
export default {
state,
getters
}
第二,您似乎使用了错误的mapGetters。如果您像上面一样设置商店,则可以在pages / index.vue中使用它,如下所示:
// pages.index.vue
<script>
import {mapGetters} from 'vuex'
export default {
computed: {
...mapGetters ({
allposts: 'posts/allPosts'
})
}
}
</script>
然后,您可以像访问任何计算的属性一样访问模板中的“ allPosts”,也可以在脚本中使用“ this.allPosts”来访问它。
答案 1 :(得分:0)
我尝试了 Andrew1325 的建议,因为我与 NUXT 和 VUEX 处于类似的位置,但它不起作用,我仍然得到:[vuex] 未知 getter:allTodos