VueJS: Respond to state changes via mapGetters by getting arguments

Question

How to pass arguments in getterinside mapGetters? Is it right to react to a change in state at widgetFetched.postsand postsat the same time? In other words, can my getterreact to these changes?


Explanation

I am trying to get my component to respond to a change Statein my Vuex Storeon getter. For this, I use mapGettersinside my component. But this one gettergets an argument idto filter my state (which is smoothed out).

I have two states (dictionaries): widgetsFetchedand posts. One widgetFetchedhas a property poststhat is an array Post.Id. And state postsis a dictionary whose keys Post.Id.

So, I have getter, called getPostsByWidgetId, which takes one argument widgetId. Then my getterreturns an array containing the messages filtered by widgetFetched.postsids.


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

enter image description here


enter image description here

+4
source share
1 answer

mapGettersDoesn't support passing arguments right now . But you can achieve a similar effect with this code:

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

Source: https://habr.com/ru/post/1686616/


All Articles