How To Pass Arguments To The Vuex Getters
CodErdal
Posted on September 27, 2022
We use Vuex to do more systematic state management with Vue JS.
Getters with a Vuex property are written like functions but work like computed properties.
Sometimes; When using getters in Vuex, in some cases we may want to send some arguments to our getters.
To do this we can use the "Method-Style Access" method provided by vuex.
Using this method we should define our getters like this:
Defining:
getterName: (state) => (parameter) => { // get the parameter
return state.data.find(item => item.id === parameter)
}
Using this defining method, we can send arguments to the getters we define.
Usage:
store.getters.getterName(2); // we sent 2 as getter parameter
But sometimes we can include our getters with the "mapGetters" helper.
In this case, we must use a different method to send arguments to the getters.
Sending arguments to getter included with mapGetters
After defining the getter with the same method, we include it in the component with "mapGetters".
To send an argument to a getter included with mapGetters; we need to define a new computed property.
This new computed property will take parameter like a function. It will send this parameter as an argument to the getter that comes with mapGetters and return this value.
import { mapGetters } from 'vuex';
computed: {
// import the getters with mapGetters
...mapGetters([
'getterName',
]),
//Define New Computed Property
newGetter(parameter){ // get the parameter
return this.getterName(parameter) // return the value
}
}
Thus, the arguments we send to our getter named newGetter will be sent to the getter we include with mapGetters.
Method-Style Access:
https://vuex.vuejs.org/guide/getters.html#method-style-access
Posted on September 27, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.