尝试使用 Vuex 并出现此错误:无法读取未定义的属性(读取“状态”)

问题描述 投票:0回答:1

我想使用 vuetify 构建一个博客,我有博客视图来显示所有帖子,并有 PostView 在单击“阅读更多”后显示其中一篇帖子 这是我的 store.js 代码

    import Vue from 'vue'
    import Vuex from 'vuex'
    // import store from './store'

    Vue.use(Vuex)
    
    export default ({
  state: {
    posts: [
      {
        id: '1',
        name: 'What Is Django & Why To Choose Django?',
        dd: 'Django is a popular web framework written in Python — one of the top web development languages — that allows you to build web applications quickly and efficiently. Its main goals are simplicity, flexibility, r....',
        image:
        'https://img.freepik.com/free-photo/close-up-hand-writing-notebook-top-view_23-2148888824.jpg?w=740&t=st=1687011561~exp=1687012161~hmac=2805395157c5393a43be29f2eac444f0e553df2172739e512495a52f0ec66890'
      },
     ...
    ]
  },
  mutations: {
    setPosts (state, posts) {
      state.posts = posts
    },
    selectPost (state, post) {
      state.selectedPost = post
    }
  },
  getters: {
    allPosts (state) {
      return state.posts
    },
    selectedPost (state) {
      return state.selectedPost
    }
  }
})

还有这个 main.js 代码

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store/store'


Vue.config.productionTip = false

new Vue({
  store: store,
  router,
  vuetify,
  created () {
    AOS.init({ once: true })
  },

  render: h => h(App)
}).$mount('#app')

这是blogView.vue

<script>
import { mapState } from 'vuex'
export default {
  computed: {
    ...mapState('store', ['posts?'])
  }
}
</script>

并且它不显示任何帖子...

vue.js vuex
1个回答
0
投票

您必须在商店状态中初始化 selectedPosts:

  state: {
    posts: [
      {
        id: '1',
        name: 'What Is Django & Why To Choose Django?',
        dd: 'Django is a popular web framework written in Python — one of the top web development languages — that allows you to build web applications quickly and efficiently. Its main goals are simplicity, flexibility, r....',
        image:
        'https://img.freepik.com/free-photo/close-up-hand-writing-notebook-top-view_23-2148888824.jpg?w=740&t=st=1687011561~exp=1687012161~hmac=2805395157c5393a43be29f2eac444f0e553df2172739e512495a52f0ec66890'
      },
     ...
    ],
    selectedPost: null // Add this line
  },

并在您的博客视图中:

<script>
import { mapState } from 'vuex'
export default {
  computed: {
    ...mapState(['posts']) // corrected mapping
  }
}
</script>
© www.soinside.com 2019 - 2024. All rights reserved.