4👍
Try to use an arrow function for your setTimeout, as the setTimeout points the this to the global object. Arrow functions use lexical scoping and knows to bind the this to the inner function:
new Vue({
el: "#exercise",
data: {
value: 0,
timer: 1000,
color:'pink',
},
methods:{
red() {
this.color = "red";
setTimeout(() => {
this.color = "";
}, 1000);
}
},
computed: {
result: function() {
return this.value >= 37 ? "Not there yet" : "done";
}
},
watch: {
result: function(value) {
var vm = this;
console.log(value);
setTimeout(function() {
vm.value = 0;
}, 5000);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="exercise">
<div>
<p>Current Value: {{ value }}</p>
<button @click="red();" :style="{ 'background-color': color }">Add 5</button>
<button @click="value += 1">Add 1</button>
<p>{{ this.result }}</p>
</div>
<div>
<input type="text" v-model="timer">
<p>{{ value }}</p>
</div>
</div>
(Also, inside of your setTimeout, you were trying to change this.red = 0, when it should be this.color = “” 😀
- [Vuejs]-How can i use filter using Vue 2 which should be compatible for Vue 3
- [Vuejs]-Write Vue plugin with custom options
Source:stackexchange.com