Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

242
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!