Search code examples
vue.jsvuejs2statevuexflux

Vuex reactive mapGetters with arguments passed through


I have lots of getters that pass arguments to the store such as:

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

And I'm not finding recommendations for how to optimally use mapGetters to maintain reactivity, while passing the arguments through. One suggestion I found was to map the getter and then pass the argument in mounted:

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

This really seems to be sub-optimal, as it would only check for a change to state on mounted. Any suggestions for how to best maintain reactivity while passing an argument to a getter? Here's an example of a getter that would match the above code:

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

Solution

  • Here is a snippet from a project I have:

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

    This makes this.account reactive and dependent on the param.

    So...

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