Search code examples
javascriptvue.jsvuex

Passing parameters to Vuex getters from a Vuex action


I have a Vuex getter that I call from various components in my application. However, I have found a case were slightly more complex logic is required before calling the getter, so I am making use of a Vuex Action. How can I call the getter function with a parameter from my action?

I use constants for naming getters/mutations/actions, so my getter is defined as follows: [GETTER_NAME]: state => param => { return {/.../} }. In my Vuex action, I would like to call the getter as follows getters[GETTER_NAME](someParam). However, this does not seem to work (even though getters[GETTER_NAME] returns a function).

Calling the getter from a component works perfectly fine. I simply create computed function and use ...mapGetters({getterName: GETTER_NAME}). To call the getter with a parameter I just say getterName(someParam).

[GETTER_NAME]: state => param=> {
    return {/.../}
},

[ACTION_NAME]: (context, param) => {
    getters[GETTER_NAME](param)
      ? context.commit(MUTATION_X, param)
      : context.commit(MUTATION_Y, param);
}

The getter gets called, however, it returns the function without passing in the parameter. Am I doing something wrong or am I misunderstanding the way getters work in Vuex?


Solution

  • You need to call like context.getters[GETTER_NAME](someParam) inside actions here.

    [GETTER_NAME]: state => param=> {
    return {/.../}
    },
    
    [ACTION_NAME]: (context, param) => {
       context.getters[GETTER_NAME](param)
         ? context.commit(MUTATION_X, param)
         : context.commit(MUTATION_Y, param);
    }