<template>
  <div>
    <h1>{{ time }}</h1>
  </div>
</template>
<script>
export default {
  data() {
    return {
      time: '5:00',
      timer: null
    }
  },
  mounted() {
    this.startTimer()
  },
  methods: {
    startTimer() {
      let minutes = 5
      let seconds = 0

      this.timer = setInterval(() => {
        if (seconds === 0) {
          if (minutes === 0) {
            clearInterval(this.timer)
            return
          }
          minutes--
          seconds = 59
        } else {
          seconds--
        }

        this.time = `${minutes}:${seconds.toString().padStart(2, '0')}`
      }, 1000)
    }
  }
}
</script>
<p>在上面的示例中,我们首先在<code>data</code>中定义了<code>time</code>和<code>timer</code>变量。<code>time</code>用于存储倒计时的时间,<code>timer</code>用于存储计时器的引用。</p>
<p>在<code>mounted</code>生命周期钩子中,我们调用<code>startTimer</code>方法来启动倒计时。</p>
<p><code>startTimer</code>方法使用<code>setInterval</code>函数来设置每秒钟更新一次倒计时。在每次更新中,我们首先检查秒数是否为0。如果是0,我们将分钟减1,并将秒数设为59。如果分钟也是0,则清除计时器并返回。</p>
<p>最后,我们将更新后的时间字符串赋值给<code>time</code>变量,以在模板中显示倒计时。</p>
<p>希望这个例子能帮到你!</p>

原文地址: https://www.cveoy.top/t/topic/pKRV 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录