Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
194
rated 0 times [  195] [ 1]  / answers: 1 / hits: 92722  / 8 Years ago, fri, january 6, 2017, 12:00:00

Is there a way to pass parameter into getter of vuex store?
Something like:



new Vuex.Store({
getters: {
someMethod(arg){
// return data from store with query on args
}
}
})


So that in component I could use



<template>
<div>
<p>{{someMethod(this.id)}}</p>
</div>
</template>
<script lang=ts>
import { mapGetters } from vuex

export default {
props: ['id'],
computed: mapGetters(['someMethod'])
}
}
</script>


but in vuex first argument is state and second is other getters. Is it possible?


More From » vue.js

 Answers
5

One way to do this can be:


new Vuex.Store({
getters: {
someMethod(state){
var self = this;
return function (args) {
// return data from store with query on args and self as this
};
}
}
})

However, getter does not take arguments and why is explained in this thread:



the naming convention is slightly confusing, getters indicates state can be retrieved in any form, but in fact they are reducers.


Perhaps we should have reducers being pure methods. Which can be used for filtering, mapping ect.


getters then can be given any context. Similar to computed, but you can now combine computed props to getters in vuex option. Which helps structure of components.



Edit:


A better way to achieve the same thing will be using ES6 arrow as detailed out in the answer of nivram80, using method style getters where you can pass a parameter by returning a function form the getter:


new Vuex.Store({
getters: {
someMethod: (state) => (id) => {
return state.things.find(thing => thing.id === id)
}
};
}
})

[#59440] Wednesday, January 4, 2017, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
josefn

Total Points: 251
Total Questions: 93
Total Answers: 84

Location: Senegal
Member since Fri, Aug 21, 2020
4 Years ago
;