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

378
Visualizações
Why can't I access data() using 'this' directly?

I work on Vue2 app. What I have noticed is sometimes I can't access elements stored in data() using this directly in my code. What I mean by that is that sometimes I need to assign this... to a variable inside a method to make it work instead of simply refer to data element by this.

I created reproducible example here: https://codesandbox.io/s/vue-2-playground-vuex-drag-and-snap-to-tiles-this-usage-trhd72?file=/src/components/ZimModel.vue

Please take a look at method addRegals(). I used this.size everywhere in this method but what I got in console is this error:

[Vue warn]: Error in callback for watcher "regalsTotalNumber": "TypeError: this is undefined"

I don't get why there's an error if I simply refer to data() element using this. To make my code work you need to uncomment code in this method (and comment not working lines). It all starts with assigning data element to variable:

var size = this.size;

I don't understand why I need to make a variable and assign this.size to it instead of explicitly using this in my method. Same situation with var tiles = this.thetiles in the same method (I also need to assign it to var to make it work in this method).

Method addRegals is triggered in watcher. Maybe here is a problem?

PS. Please type '120' as length, '55' as width in input fields (give it a few sec to show the grid on a screen), then type some number in 'Regals number' field.

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

0

You have defined a local function named getPos inside the addRegals method. The only problem is that getPos does not share this with addRegals. However, when you declare the variable, it is available in the getPos closure.

The solution would either be to make getPos a local lambda function or make it a method.

You can read more on this in Javascript here: https://www.freecodecamp.org/news/the-complete-guide-to-this-in-javascript/.

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