+-
如何在Vue.js中创建简单的10秒倒计时

我想做一个从10到0的简单倒计时

我使用普通的javascript在线找到了解决方案但是我想在Vue中做到这一点。 Jquery中的解决方案

Create a simple 10 second countdown

<template>
   {{ countDown }}

</template>

<script>
  export default {
    computed: {
       countDown() {
         // How do i do the simple countdown here?
       }

    }

  }

</script>

如何在Vue.js中重新创建相同的功能?

谢谢

2
投票

请检查这是否适合您。

<template>
   {{ countDown }}
</template>

<script>
    export default {
        data() {
            return {
                countDown : 10
            }
        },
        method: {
            countDownTimer() {
                if(this.countDown > 0) {
                    setTimeout(() => {
                        this.countDown -= 1
                        this.countDownTimer()
                    }, 1000)
                }
            }
        }
        created: {
           this.countDownTimer()
        }
    }
</script>
0
投票

这是我为倒数计时器制作的一个组件:

<template>
  <div>
    <slot :hour="hour" :min="min" :sec="sec"></slot>
  </div>
</template>

<script>
export default {
  props : {
    endDate : {  // pass date object till when you want to run the timer
      type : Date,
      default(){
        return new Date()
      }
    },
    negative : {  // optional, should countdown after 0 to negative
      type : Boolean,
      default : false
    }
  },
  data(){
    return{
      now : new Date(),
      timer : null
    }
  },
  computed:{
    hour(){
      let h = Math.trunc((this.endDate - this.now) / 1000 / 3600);
      return h>9?h:'0'+h;
    },
    min(){
      let m = Math.trunc((this.endDate - this.now) / 1000 / 60) % 60;
      return m>9?m:'0'+m;
    },
    sec(){
      let s = Math.trunc((this.endDate - this.now)/1000) % 60
      return s>9?s:'0'+s;
    }
  },
  watch : {
    endDate : {
      immediate : true,
      handler(newVal){
        if(this.timer){
          clearInterval(this.timer)
        }
        this.timer = setInterval(()=>{
          this.now = new Date()
          if(this.negative)
            return
          if(this.now > newVal){
            this.now = newVal
            this.$emit('endTime')
            clearInterval(this.timer)
          }
        }, 1000)
      }
    }
  },
  beforeDestroy(){
    clearInterval(this.timer)
  }
}
</script>
0
投票

所以基本上在vue.js中执行它与在JS中执行它相同。 您可以遵循许多路径,但我将采取的方式如下

<template>
    {{ countDown }}
</template>

<script>
    export default {
    created() {
        window.setInterval(autoIncrementTimer, 1000)
    },
    methods() {
        autoIncrementTimer() {
            if (this.timerCount =< 0) {
                return
            }
            timerCount -= 1;
        }
    }
    data() {
        return {
               timerCount: 0;
        }
    },
}

</script>

为了将其作为计算属性来执行,您需要编写一个get和set函数,并且整体计算出来的道具对于此任务来说似乎有些过分。

总结一下:

在数据中创建变量,以存储当前值。 在Component Create()上使用window.setInterval创建一个循环函数和间隔时间。 在您的功能中,根据需要应用安全和减量。

如你所见,上面的<script>实际上是vanilla js。