[Vuejs]-Why element isn't hidden after changes of v-show attribute?

1👍

This directly sets show to true:

console.log(false);
setTimeout(() => console.log("done"), 5000);
console.log(true);

setTimeout takes a function to be executed after the timeout, this is where you need to change the variable:

new Vue({
  el: "#app",
  data: { show: true },
  methods: {
    change: function () {
      this.show = false;
      setTimeout(() => this.show = true, 5000);
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <p v-show="show">test</p>
  <button v-on:click="change">btn</button>
</div>

2👍

setTimeout doesn’t work like that.

It doesn’t stop there, wait and continue after 5 seconds. It continues immediately to next step, so you immediately change show to true.

setTimeout calls it’s callback asynchronously, meaning it will call the function you give it after 5 seconds.

So you need to do it like this:

setTimeout(() => this.show = true, 5000);

1👍

Try running the toggle inside of the setTimeout

setTimeout(() => {
  this.show = true;
}, 5000);
👤kissu

Leave a comment