Home > Net >  Can I set classname to change after a few seconds?
Can I set classname to change after a few seconds?

Time:09-03

I'm using vue.js to set data boolean to change after a few seconds with setTimeout, but the result shows that the data remain same. If I have already returned the data value, what's causing this?

new Vue({
  el: "#app",
  data: {
    showMsg: false,
  },
  methods: {
    activeMsg() {
      this.showMsg = true
      this.msgNone
    }
  },
  computed: {
    msgNone() {
      const msgCounter = setTimeout(()=>{
        clearTimeout(msgCounter)
        return this.showMsg = false
      },2500)
    },
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <button @click="activeMsg">click me</button>
  <p v-if="showMsg">hello</p>
</div>

CodePudding user response:

computed property doesn't do asynchronous calls, Just called the setTimeout inside the method:

new Vue({
  el: "#app",
  data: {
    showMsg: false,
  },
  methods: {
    activeMsg() {
      this.showMsg = true
      const msgCounter = setTimeout(() => {

        this.showMsg = false
        clearTimeout(msgCounter)
      }, 2500)
    }
  },

})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <button @click="activeMsg">click me</button>
  <p v-if="showMsg">hello</p>
</div>

  • Related