我一直在尝试使用 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 处理此类事情的方式是什么?
不要认为这与 React 或 Vue 有任何关系。您需要清除回调中的间隔setInterval,以便它知道何时停止。不需要循环while:
this.interval = setInterval(() => {
if (this.timer === 0) {
clearInterval(this.interval)
} else {
this.timer--
}
}, 1000)
Run Code Online (Sandbox Code Playgroud)
另请查看这个纯 js 示例:
let timer = 10;
let interval = setInterval(() => {
if (timer === 0) {
clearInterval(interval)
} else {
timer--
console.log(timer)
}
}, 1000)Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12337 次 |
| 最近记录: |