【问题标题】:VueJS: React to State change through mapGetters receiving argumentsVueJS:通过接收参数的 mapGetters 对状态变化做出反应
【发布时间】:2018-03-11 02:19:16
【问题描述】:

问题

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


说明

我正试图通过getter 使我的组件对我的Vuex Store 中的State 的更改做出反应。为了实现这一点,我在我的组件中使用了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>

示例


【问题讨论】:

    标签: javascript vue.js vuejs2 vuex


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2020-05-18
      • 2021-06-06
      • 2020-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-14
      • 2022-07-22
      • 1970-01-01
      相关资源
      最近更新 更多