Vue 2 - vuex mapGetters and pass params
Is it possible to pass parameters using mapGetters ?
I have this in my main Vue instance:
computed: {
filterAuthors() {
return this.$store.getters.filterAuthors(this.search.toLowerCase());
}
}
this.search binds to the input field using 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 works great, but I'm trying to find a way (if possible) to use mapGetters and pass an argument. It can be done?
source to share
It really can be done! mapGetters just 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())
}
}
}
source to share
This is the closest thing you can do if you want to pass a parameter to the store. However, a better way to deal with this would be to make the parameter as part of the store too, and set the field input
as a computed property with an appropriate getter and setter to update the state. And then you can use mapGetter
to get results.
const { mapGetters } = Vuex
const authorsInput = [{ name: 'Stephen King'}, { name: 'Neal Stephenson'}, { name: 'Tina Fey'}, { name: 'Amy Poehler'}, { name: 'David Foster Wallace'}, { name: 'Dan Brown'}, { name: 'Mark Twain'}]
const store = new Vuex.Store({
state: {
srchInput: '',
authors: authorsInput
},
getters: {
filteredAuthors: (state) => state.authors
.filter((author) => author
.name
.toLowerCase()
.indexOf(state.srchInput.toLowerCase()) >= 0)
.map((author) => author.name)
},
mutations: {
UPDATE_SRCH_INPUT: (state, input) => state.srchInput = input
},
})
new Vue({
el: '#app',
store,
computed: Object.assign({
srchInput: {
get () { return store.state.srchInput},
set (val) { store.commit('UPDATE_SRCH_INPUT', val) }
}
}, mapGetters([
'filteredAuthors'
]))
})
filterAuthors: (state) => (search) => {
return state.authors.filter((author) => {
return author.name.toLowerCase().indexOf(search) >= 0;
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/2.3.1/vuex.js"></script>
<div id="app">
<div>
<input type="text" v-model="srchInput"/>
<ul>
<li v-for="author in filteredAuthors">{{author}}</li>
</ul>
</div>
</div>
source to share