[Vuejs]-Struggling to show then hide success alert using Vue

2πŸ‘

βœ…

An alternative to using a setTimeout on the method is to add a watch and include a setTimeout there. This has the advantage that anything causing this value to be set will be cleared after the requesite time, and it can’t be triggered multiple times (as it will only react when the value is changed to true). Modified fiddle here. The changed code block (I used a 1s timeout just because I’m impatient during testing ;)):

new Vue({
  el: "#app",
  data() {
    return {
      testButClicked: false
    }
  },
  methods: {
    testToast() {
      this.testButClicked = true;
    }
  },
  watch:{
    testButClicked(val){
      if (val){
        setTimeout(()=>this.testButClicked=false,1000);
      }
    }
  }
})

3πŸ‘

You can just add the setTimeout in the function. Regardless of if this function is a click handler or not.

new Vue({
  el: "#app",
  data() {
    return {
      testButClicked: false
    }
  },
  methods: {
    testToast() {
      this.testButClicked = true;
      setTimeout(() => {
        this.testButClicked = false
      }, 5000)
    }
  }
})
body {
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

.alert {
  background-color: lightgreen;
  padding: 15px;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 1.3s ease;
}

.fade-enter,
.fade-leave-to {
  opacity: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <button type="button" @click="testToast">TEST BUTTON</button>
  <br><br>
  <transition name="fade" mode="out-in">
    <div v-if="testButClicked" class="alert" role="alert">
      Item successfully added to your cart
    </div>
  </transition>
</div>

Leave a comment