Raphael Parreira Raphael Parreira - 3 years ago 228
Javascript Question

VueJS: React to State change through mapGetters receiving arguments

Question



How can I pass arguments to a
getter
inside
mapGetters
? Is this on the right way to react a state change on
widgetFetched.posts
and
posts
at the same time? In other words, can my
getter
react to these changes?




Explanation



I'm trying to make my Component react to a change in
State
in my
Vuex Store
through a
getter
. To achieve this, I'm using
mapGetters
inside my Component. But this
getter
receives an argument, an
id
to filter my state (that is flatten).

I have two states (that are dictionaries):
widgetsFetched
and
posts
. One
widgetFetched
has a property called
posts
that is an array of
Post.Id
. And the state
posts
is a dictionary whose keys are
Post.Id
.

So, I have a
getter
called
getPostsByWidgetId
that takes one argument
widgetId
. Then, my
getter
returns an array containing posts filtered by
widgetFetched.posts
's ids.




Store



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 looks like:

<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



enter image description here




enter image description here

Answer Source

Right now, mapGetters do not support pass argument. But you can achieve it with this code:

computed: {
  posts() {
    return this.$store.getter.getPostsByWidgetId(this.widget._id)
  }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download