Reputation: 91
I am having a problem in my Vuex.Store:
I would like to get an object (getter.getRecipe) using two state entries as search criteria (state.array & state.selected) with a getter. Then I would like to store that result in my state (state.recipe) in order to be able to update it within components (i.e., changing one key of the recipe object based on client action). However, I have no idea how I can store the result of getters in my state ("this.getters.getRecipe" is not working...). Very helpful for hints. Thanks a lot.
//store.js (vuex store)
export const store = new Vuex.Store({
state: {
array: [recipe1, recipe2],
selected: 0,
recipe: this.getters.getRecipe()
},
getters: {
getRecipe: (state) => {
return state.array[state.selected]
}
}
})
Upvotes: 0
Views: 2800
Reputation: 7165
Instead, you should use Method style getters with arguments:
You can also pass arguments to getters by returning a function. This is particularly useful when you want to query an array in the store:
A basic example:
getters: {
// ...
getTodoById: (state) => (id) => {
return state.todos.find(todo => todo.id === id)
}
}
Then, to use the example:
store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }
or, from inside a component:
this.$store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }
This way you ensure your state remains a pure data structure that follows the one way data flow set forth by the flux pattern.
Upvotes: 1