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

238
Visualizações
Vuejs not changing view on variable change

I'm having an issue where after 5 seconds, the text isn't updating. Can someone please help me figure out what I need to make it change on the browser after 5 seconds?

<template>
  <h1>{{ test }}</h1>
</template>

<script>
export default {
  data() {
    return {
      test: 'Foo'
    }
  },
  mounted() {
    setTimeout(function(){ 
      this.test = 'Bar'
    }, 3000);
      
  }
}
</script>
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

In the setTimeout funciton, use an arrow function as follow:

setTimeout(() => {
  this.test = "Bar";
}, 3000);

See https://codesandbox.io/s/fervent-glitter-l3j5s?file=/src/App.vue:160-217 for an example.

The reason is the context (this) is different with a normal and an arrow function. See https://www.w3schools.com/Js/js_arrow_function.asp section "What About this?" for more.

over 4 years ago · Santiago Trujillo Relatório

0

mounted function has it's own this binding, and when you create a another anonymous function, it also has it's own this binding, which is different from this of mounted.

I would suggest you the classical way: keep a reference to this and use it in the function, this will always work.

mounted() {
    const that = this;

    setTimeout(function(){ 
      that.test = 'Bar'
    }, 3000);
      
  }

Once you got familiar with scope and arrow function, you can use arrow function to make your code shorter and cleaner. Actually there are no this binding to arrow function, which is a little hard to feel and understand at the beginning.

over 4 years ago · Santiago Trujillo 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