接受参数并使用VueX在getter中过滤

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

我一直在嘲笑这个。我试图用一个getter来检索一个对象(博客文章)的“slug”。但是,无论这个getter的任何实现,我的state.posts.filter都会一直返回“state.posts.filter”不是一个函数。我确信状态在数组中有项目,默认情况下它被定义为数组。所以任何想法为什么会这样做?根据我的代码片段,假设已经调度了FETCH_POSTS,并且帖子中有元素。

我不知道这是否会影响它,但我也在模块化商店格式的Nuxt中使用它。

我的商店:

import {createClient} from '~/plugins/contentful.js'
const client = createClient()

const state = {
   posts: []
}

// getters
const getters = {
   allPosts: state => state.posts,
   getPostBySlug: state => slug => state.posts.filter(post => post.fields.slug === slug)
}

// actions
const actions = {
   FETCH_POSTS: (state) => {
   // INIT LOADING
   client.getEntries({
     'content_type': 'article',
     order: '-sys.createdAt'
   })
  .then(posts => {
    // SUCCESS
    state.commit('SET_POSTS', posts.items)
  })
  .catch(error => {
    // FAILURE
    console.log(error)
  })
 }
}

// mutations
const mutations = {
   SET_POSTS: (state, posts) => {
      // Assign posts to state
      posts = posts.map(function (post) { post.fields.slug = post.fields.title.replace(/\s+/g, '-').toLowerCase()
      return post
   })
   state.posts = Object.assign({}, posts)
  }
}

export default {
 state,
 getters,
 actions,
 mutations
}

我在我的组件中调用它是这样的:

export default {
    name: 'blog-post',
    computed: {
      post: function () {
        return this.$store.getters.getPostBySlug('test-slug')
      }
    }
}
javascript vue.js vuex nuxt.js
1个回答
0
投票

@Bert和@Evaldo提供了正确的答案。调度我的“SET_POST”突变时,我的初始分配是将结果分配给空对象,而不是相应的数组。正确的实施将如下。

// mutations
const mutations = {
   SET_POSTS: (state, posts) => {
      // Assign posts to state
      posts = posts.map(function (post) { post.fields.slug = post.fields.title.replace(/\s+/g, '-').toLowerCase()
         return post
      })
      state.posts = Object.assign({}, posts)
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.