How To Pass Arguments To The Vuex Getters

coderdal

CodErdal

Posted on September 27, 2022

How To Pass Arguments To The Vuex Getters

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)
}
Enter fullscreen mode Exit fullscreen mode

Using this defining method, we can send arguments to the getters we define.

Usage:

store.getters.getterName(2); // we sent 2 as getter parameter
Enter fullscreen mode Exit fullscreen mode

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
    }

  }
Enter fullscreen mode Exit fullscreen mode

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

💖 💪 🙅 🚩
coderdal
CodErdal

Posted on September 27, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

State Management Showdown Vuex vs. Pinia
javascript State Management Showdown Vuex vs. Pinia

February 25, 2024

Vuex
webdev Vuex

April 25, 2023

How To Pass Arguments To The Vuex Getters
javascript How To Pass Arguments To The Vuex Getters

September 27, 2022