[Vuejs]-Toggle visibility using v-show or v-if in Vue while using a setTimeout function

1👍

Your main issue is this inside the setTimeout callback

Because you use function() {} it’s NOT what you want this to be

Either use arrow notation setTimeout(() => {}, 2000)

updateProduct(product) {
  this.isHidden = true;
  setTimeout(() => {
    //do a bunch of tasks that work correctly... 
    axios.post('/api/product/' + product.id, data)
      .then(function(response) {
        console.log(response);
      }).catch(function(error) {
        console.log(error);
      });
    this.isHidden = false;
  }, 2000);
}

Or, if arrow notation scares you setTimeout(function() {}.bind(this), 2000)

updateProduct(product) {
  this.isHidden = true;
  setTimeout(function() {
    //do a bunch of tasks that work correctly... 
    axios.post('/api/product/' + product.id, data)
      .then(function(response) {
        console.log(response);
      }).catch(function(error) {
        console.log(error);
      });
    this.isHidden = false;
  }.bind(this), 2000);
}

As a side note, do not use alert for debugging – it blocks execution of javascript and can lead to unreliable debugging results

-1👍

Just Use V-else

<div v-if="!this.isHidden"> <!--or v-else -->
  <form @submit.prevent="">
  <!--Fields-->
  <button @click="updateProduct(product)" type="button">Submit</button>
  </form>
</div>

<div v-else>
<div v-if="this.isHidden">
 LOADING....
</div>
</div>

Leave a comment