【发布时间】:2017-12-19 16:15:29
【问题描述】:
我一直在为此绞尽脑汁。我正在尝试使用 getter 通过其“slug”检索对象(博客文章)。然而,不管这个 getter 的任何实现,我的 state.posts.filter 一直返回“state.posts.filter”不是一个函数。我确信 state 在数组中有项目,默认情况下它被定义为一个数组。那么知道为什么它会这样吗?根据我的 sn-p,假设 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')
}
}
}
【问题讨论】:
-
state.posts = Object.assign({}, posts)此代码不正确。您正在设置帖子等于一个新对象。对象绝对没有filter方法。也许,state.posts = posts.slice(0)? -
除了@Bert,
state.posts = [...posts]也可以完成这项工作 -
@Bert & Evaldo - 你们两个是绝对正确的。不知道为什么我最初是这样实现的,但我的眼睛完全忽略了它。感谢您的帮助!
标签: javascript vue.js vuex nuxt.js