Reputation: 1089
Pinia. In Setup Stores: ref()s become state properties, computed()s become getters, function()s become actions.
Vuex. Method-Style Access. 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:
getters: {
// ...
getTodoById: (state) => (id) => {
return state.todos.find(todo => todo.id === id)
}
}
store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }
Not work
const getItemsByType = computed((element: string) => {
return data.value[element] ? data.value[element] : []
})
That is like action but with return and also not help
const getItemsByType = (element: string) => {
return computed((element: string) => {
return data.value[element] ? data.value[element] : []
})
}
That work, but that is an action and not getter(if consider that a getter is only with computed()) and is not cached
const getItemsByType = (element: string) => {
return data.value[element] ? data.value[element] : []
}
Upvotes: 2
Views: 373
Reputation: 1089
Maintainer @posva answer https://github.com/vuejs/pinia/discussions/1569#discussioncomment-3429724
It's actually the same as Vuex
Options stores:
defineStore('store', {
getters: {
foo: state => (param) => state.bar + param
}
})
Setup Stores:
const getItemsByType = computed(() =>
(element: string) => data.value[element] ? data.value[element] : []
)
Upvotes: 0
Reputation: 37753
Computed cannot have an argument.
From Vuex docs:
Note that getters accessed via methods will run each time you call them, and the result is not cached.
So the Method-Style Access in Vuex is just a getter returning function. Equivalent in Pinia is to use plain function (last example)
const getItemsByType = (element: string) => {
return data.value[element] ? data.value[element] : []
}
Upvotes: 3