Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue 2 - vuex mapGetters and pass params

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?

like image 832
Sasha Avatar asked Aug 01 '17 12:08

Sasha


1 Answers

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())
    }
  }
}
like image 97
David Roberts Avatar answered Sep 23 '22 19:09

David Roberts