传递参数的Vuex反应式地图获取器

2022-06-27 state vue.js vuejs2 vuex flux

我有很多将参数传递给存储的getter方法,例如:

this.$store.getters['getSomeThing'](this.id)

我没有找到关于如何在传递参数的同时以最佳方式使用mapGetters来保持反应性的建议。我发现的一个建议是映射获取方法,然后在mount中传递参数:

computed: {  
  ...mapGetters([
    'getSomeThing'
  ])
},
mounted () {
  this.getSomeThing(this.id)
}
这看起来确实不太理想,因为它只会检查是否更改了挂载时的状态。对于如何在将参数传递给getter时最好地保持反应性,有什么建议吗?下面是一个与上述代码匹配的getter示例:

getSomeThing: (state) => (id) => {
  return state.things.find(t => { return t.id === id })
}

解决方案

以下是我的一个项目的片段:

    computed: {
        ...mapGetters('crm', ['accountWithId']),
        account() {
            return this.accountWithId(this.$route.params.id)
        }
    },

这使this.account被动并依赖于参数。

所以...

computed: {  
  ...mapGetters([
    'getSomeThing'
  ]),
  thing() {
    return this.getSomeThing(this.id)
  }
},

相关文章