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?
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);
}
In actions have injected parameters : dispatch
, commit
, getters
and rootState
. Therefore you can access getters like this:
ACTION_NAME: ({ commit, getters }, payload) => {
let MY_VARIABLE = getters.GETTER_NAME(payload)
console.log(MY_VARIABLE)
}
This works fine even if you try to access a getter from a different module.
Though you can use getters with context via context.getters
the syntax gets a bit longish inside the action when using it this way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With