如何在 Vue3 中进行简单的倒计时?

时间:2021-01-08 22:52:59

标签: vue.js vuejs3

我一直在尝试使用 Vue3 设置一个简单的倒计时,但我无法让它正常工作。这在 React 中很容易实现,但我根本不明白 Vue (3) 中的逻辑。所以,我想出了这个:

<script>
export default {
    data() {
        return {
            timer: 10,
            interval: ""
        }
    },
    emits: ["start-game"],
    methods: {
        startGame() {
            this.$emit("start-game")

            this.startTimer()
        },
        startTimer() {
            clearInterval(this.interval)

            while(this.timer != 0) {
                this.interval = setInterval(() => {
                    this.timer--
                }, 1000)
            }
        }
    }
}
</script>

您希望这会起作用,但它会造成无限循环。不知何故,你不能只在 vue 方法中使用 while。如果我删除 while 它实际上无限期地倒计时,但是一旦计时器用完(命中 0),我需要其他函数来运行。 Vue 的处理方式是什么?

1 个答案:

答案 0 :(得分:1)

不要认为这与 React 或 Vue 有任何关系。您需要清除 setInterval 回调中的间隔,以便它知道何时停止。不需要 while 循环:

this.interval = setInterval(() => {
  if (this.timer === 0) {
    clearInterval(this.interval)                
  } else {
    this.timer--
  }             
}, 1000)

还可以查看这个纯 js 示例:

let timer = 10;
let interval = setInterval(() => {
  if (timer === 0) {
    clearInterval(interval)                
  } else {
    timer--
    console.log(timer)
  }             
}, 1000)

相关问题