Question
How to pass arguments in getter
inside mapGetters
? Is it right to react to a change in state at widgetFetched.posts
and posts
at the same time? In other words, can my getter
react to these changes?
Explanation
I am trying to get my component to respond to a change State
in my Vuex Store
on getter
. For this, I use mapGetters
inside my component. But this one getter
gets an argument id
to filter my state (which is smoothed out).
I have two states (dictionaries): widgetsFetched
and posts
. One widgetFetched
has a property posts
that is an array Post.Id
. And state posts
is a dictionary whose keys Post.Id
.
So, I have getter
, called getPostsByWidgetId
, which takes one argument widgetId
. Then my getter
returns an array containing the messages filtered by widgetFetched.posts
ids.
Score
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]
})
}
}
}
})
Component
My components look like this:
<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>
Examples

