3
votes

Assume you have a simple app component with a button to add multiple counters from a counter component using a vuex store.

Here is the whole thing on webpackbin.

A bit like the basic counter example from the vuex git repo.But you want to use the vuex getter with an ID that is handed over via a property on the component, how would you do that?

The getter has to be a pure function, so you can't use this.counterId. The official docs say you have to use a computed property, but that doesn't seem to work either. This code returns undefined for the getter:

import * as actions from './actions'

export default {
    props: ['counterId'],
    vuex: {
        getters: {
            count: state => state.counters[getId]
        },
        actions: actions
    },
    computed: {
        getId() { return this.counterId }
    },
}
1
your code seems to be right. The idea behind the "getId" computed property is for you to use properties from your Component, instead from your State. In your case, you are doing both. Nothing wrong with it, but pay attention to your logic when calling getId() and what are you getting from it.Ricardo Vigatti
the id is just the array index. the computed property itself works fine. tho the getter still returns undefined so there must be something wrong. I am using the computed property because you can't use this in the getter by definition.Chris

1 Answers

6
votes

getters should be pure functions and not dependent on component state.

you can still crate a computed prop from the getter, or directly use the store:

//option A
export default {
    props: ['counterId'],
    vuex: {
        getters: {
            counters: state => state.counters
        },
        actions: actions
    },
    computed: {
        currentCounter() { return this.counters[this.counterId] }
    },
}

//option B (better suited for this simple scenario)
import store from '../store'
computed: {
  currentCounter() {  
    return store.state.counters[this.counterId] 
  }
}