getter
mapGetters
widgetFetched.posts
posts
getter
State
Vuex Store
getter
mapGetters
getter
id
widgetsFetched
posts
widgetFetched
posts
Post.Id
posts
Post.Id
getter
getPostsByWidgetId
widgetId
getter
widgetFetched.posts
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>
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)
}
}