1

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>
1
  • 1
    This test is not that test. Change your settimeout handler into arrow function Commented Oct 12, 2021 at 17:43

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.