tl;dr
How to access other getters from a parameterized getter?
Normally, you can use this.myGetter
; but a parameterized getter is implemented as an arrow function, wherein this
is undefined.
What's the preferred way to handle this case in Pinia?
I'd like to create a parameterized getter (multiSum
) in my Pinia store, which accesses another getter (sum
).
Getters can be accessed via this
, but that won't work from within an arrow function which is used to implemented a parameterized getter: multiSum
crashes because this
is undefined
in the context of the nested arrow function.
getters: {
sum: (state) => state.a + state.b,
multiSum: (state) => (count) => this.sum * count // crash: this is undefined
}
In Vuex, parameterized getters can access other getters via a parameter instead of this
, which also works in arrow functions. But afaik this API does not existing in Pinia.
I can work around this by capturing the store instance:
multiSum(state) {
const store = this
return (count) => store.sum * count
}
This works, but is pretty verbose. Is there a better (more framework-compliant) way to do this?
this.sum
fails becausethis
inside the arrow function is undefined. Vuex provides a solution for this, by passing thegetters
object as optional argument to getters. (Will update my question.) – Fructuous