我一直在尝试使用 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>
Run Code Online (Sandbox Code Playgroud)
您希望这能起作用,但它会造成无限循环。不知何故,你不能只使用whilevue 方法内部。如果我删除它,while它实际上会无限期地倒计时,但一旦计时器用完(达到 0),我需要运行其他函数。Vue 处理此类事情的方式是什么?