Adoga Patricia
Adoga Patricia

Reputation: 129

How do I set timeout after button has been clicked in vue

I need a background colour to go back to its default colour after 3 seconds, I am using the setTimeout method but it is not working, how do I properly use it in this situation? or do I use a transition

<div id="exercise">

    <div>
      <p>Current Value: {{ value }}</p>
      <button @click="value += 5(); red();" :style="{ 'background-color': color }">Add 5</button>
      <button @click="value += 1">Add 1</button>
      <p>{{ result }}</p>
    </div>

    <div>
      <input type="text" v-model="timer">
      <p>{{ value }}</p>
    </div> 
  </div>
new Vue({
  el: "#exercise",
  data: {
    value: 0,
    timer: 1000,
    color:'pink',


  },
  methods:{
  red() {
   this.color = "red";
setTimeout(function() {
        this.red = 0;
      }, 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);
    }
  } 
});

Upvotes: 0

Views: 1852

Answers (1)

procoib
procoib

Reputation: 487

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 = "" :D

Upvotes: 4

Related Questions