Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

286
Visualizações
Accessing a getter from a parameterized getter

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?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

this can be undefined inside arrow function because it's not interchangeable with regular function and gets a context from parent scope.

The usage of this and state is explained in details in the documentation. Either this or state can be used, but this has better Typescript and thus IDE support.

In the first snippet, state is already available in function scope, there is no need to access this:

multiSum: (state) => (count) => state.sum * count

In the second snippet, const store = this isn't needed because a store is already this.

multiSum() {
  return (count) => this.sum * count
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda