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>
CodePudding user response:
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.
CodePudding user response:
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.