How to pass parameters to a Vuex store getter
the KISS way
Post by Pedro Resende on the 24 of August of 2018 at 15:49
Tags: vue.jsvuevuexgettersstoreis not a function
Today, while working on a project with Vue.js and VueX, I found an apparent limitation of the vuex store.
It seem that it's not possible to pass parameters to a getter, when it's being mapped by mapGetters.
I've declared normally my getter in the store like the following:
getters: {
getProcess: state => processId => {
return state.process.processId;
}
}
Then, imported has a computed property, inside my vue.js component
import { mapGetters } from 'vuex';
export default {
computed: {
...mapGetters(['getProcess'])
}
};
but when I tried to use it in the template section
{{ getProcess(1) }}
I was getting the following error in the browser console
TypeError: a.getProcess is not a function
Apparently is seem that you can't call directly into the template a getter from a store with parameters, therefor a way to overcome this limitation is by adding the following method into you component
methods: {
getProcessFromStore(processId) {
return this.getProcess(1);
}
}
turning your script section into the following:
<script>
import { mapGetters } from 'vuex';
export default {
computed: {
...mapGetters(['getProcess'])
},
methods: {
getProcessFromStore(processId) {
return this.getProcess(1);
}
}
};
</script>
and you only have to change your template into
{{ getProcessFromStore(1) }}
That's it, although it doesn't makes a lot of sense for not being able to inject directly the variable to the store getter, this is due to the fact of the computed properties are by default getter-only.