Vue/Nuxt/Vuex - [NUXT:SSR] [错误] [vuex] 未知 getter

Vue/Nuxt/Vuex - [NUXT:SSR] [ERROR] [vuex] unknown getter

当我使用 v-for 循环遍历 div 上的 'allPosts' 数据时出现错误。

Nuxt 文档说 'Modules: every .js file inside the store directory is transformed as a namespaced module'。也许我在这方面遗漏了什么?

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
}

您在设置和访问商店的方式上遇到了很多问题。首先,您使用 docs 告诉我们的“经典模式”创建您的商店:

This feature is deprecated and will be removed in Nuxt 3.

因此,为了使用最新的方法,您的 store/index.js 应该如下所示:

//store/index.js



//end

这不是一个错误,您实际上不需要其中的任何东西,只要让它存在即可。无需导入 vue 或 vuex 或任何模块。

你的store/posts.js基本上可以保持原样,只需要改变你的state,mutations,getters,和要导出常量的动作,并删除底部导出:

//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”访问它。