Vue 2 - vuex mapGetters and pass params

Sasha picture Sasha · Aug 1, 2017 · Viewed 20.1k times · Source

Is it possible to pass params with mapGetters?

I have this in main Vue instance:

computed: {
    filterAuthors() {
        return this.$store.getters.filterAuthors(this.search.toLowerCase());
    }
}

this.search is bind to the input field via v-model="search=, and in my Vuex instance I have this getters:

getters: {
    filterAuthors: (state) => (search) => {
        return state.authors.filter((author) => {
            return author.name.toLowerCase().indexOf(search) >= 0;
        })
    }
},

This one is working fine, but I am trying to find a way (if it is possible) to use mapGetters and to pass the argument. Can this be done?

Answer

David Roberts picture David Roberts · Jan 5, 2018

This can indeed be done! mapGetters simply maps this.yourGetterName to this.$store.getters.yourGetterName (see docs)

So to accomplish what you want:

import { mapGetters } from 'vuex'

export default {
  // ... the rest of your Vue instance/component
  computed: {
    // Mix your getter(s) into computed with the object spread operator
    ...mapGetters([
      'filteredAuthors'
      // ...
    ]),
    // Create another computed property to call your mapped getter while passing the argument
    filteredAuthorsBySearch () {
      return this.filteredAuthors(this.search.toLowerCase())
    }
  }
}