计时器一定要离开时清掉,否则会计时器内的代码在离开页面之后依旧会执行
destroyed() {
clearInterval(this.timer)
},
完整:
<template>
<div id="countDown">{{ timeNum }}</div>
</template>
<script>
export default {
name: "CountDown",
data() {
return {
timeNum: 10,
timer: null
}
},
created() {
this.countDown()
},
//离开时清除计时器
destroyed() {
clearInterval(this.timer)
},
methods: {
countDown() {
if (!this.timer) {
this.timer = setInterval(() => {
this.timeNum = this.timeNum - 1
console.log(this.timeNum,'倒计时')
if (this.timeNum <= 0) {
clearInterval(this.timer)
console.log('计时器时间到了')
}
}, 1000)
}
}
},
}
</script>
<style scoped>
</style>