Search code examples
vue.jssettimeout

How to hide elemets after certain time in vue?


I'm doing an internet-shop app in vue and when I add to cart certain products, I need to show a text, that will show ,that element is added to cart. But afer some time, I need to hide the text. How can I do that? ,when you click on Add to cart button,this text shows up. added to cart!

In mounted I tried this:

   mounted() {
   setTimeout(()=>{
    this.isAdded=false
      },1000)
}

but nothing works, text still appears there


Solution

  • new Vue({
      el: "#demo",
      data() {
        return {
          isAdded: false
        }
      },
      methods: {
        add() {
          this.isAdded = true
          setTimeout(()=>{
            this.isAdded = false
          }, 2000);
        }
      }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="demo">
      <button @click="add">add</button>
      <h1 v-if="isAdded">
        added
      </h1>
    </div>