gpt4 book ai didi

javascript - VueJS : React to State change through mapGetters receiving arguments

转载 作者:搜寻专家 更新时间:2023-10-30 22:16:49 24 4
gpt4 key购买 nike

问题

如何将参数传递给 mapGetters 中的 getter?这是同时对 widgetFetched.postsposts 的状态变化使用react的正确方法吗?换句话说,我的 getter 可以对这些变化使用react吗?


说明

我正在尝试通过 getter 让我的组件对 Vuex Store 中的 State 变化使用react。为此,我在我的组件中使用了 mapGetters。但是这个 getter 接收一个参数,一个 id 来过滤我的状态(即展平)。

我有两个状态(即字典):widgetsFetchedposts。一个 widgetFetched 有一个名为 posts 的属性,它是一个 Post.Id 数组。状态 posts 是一个字典,其键是 Post.Id

因此,我有一个名为 getPostsByWidgetIdgetter,它接受一个参数 widgetId。然后,我的 getter 返回一个数组,其中包含由 widgetFetched.posts 的 ID 过滤的帖子。


商店

const store = new Vuex.Store({
state: {
widgetsFetched: {
1: { id: 1, done: true, posts: [1, 2, 3, 4] },
2: { id: 2, done: false, posts: [5, 6] }
},
posts: {
1: { name: '...', id: 1, content: '...' },
2: { name: '...', id: 2, content: '...' },
3: { name: '...', id: 3, content: '...' },
4: { name: '...', id: 4, content: '...' },
5: { name: '...', id: 5, content: '...' },
6: { name: '...', id: 6, content: '...' }
}
},
getters: {
getPostsByWidgetId: (state, getters) => (widgetId) => {
if (widgetId && state.widgetsFetched[widgetId] && state.widgetsFetched[widgetId].posts) {
return state.widgetsFetched[widgetId].posts.map((postId) => {
return state.posts[postId]
})
}
}
}
})

组件

我的组件看起来像:

<template>
<div>
<p v-for="post in posts(this.widget._id)" >{{ post.id }} - {{ post.score }}</p>
</div>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
name: 'reddit',
props: ['widget'],
computed: {
...mapGetters({
posts: 'getPostsByWidgetId'
})
}
}
</script>

<style scoped>
</style>

例子

enter image description here


enter image description here

最佳答案

目前,mapGetters 不支持传递参数。但是你可以用这段代码达到类似的效果:

computed: {
posts() {
return this.$store.getter.getPostsByWidgetId(this.widget._id)
}
}

关于javascript - VueJS : React to State change through mapGetters receiving arguments,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46484382/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com