Vue3倒计时组件(Countdown)改写
<template>
<div>
<span v-if="!isCountdownRunning">{{ countdown }}</span>
<button v-else @click="stopCountdown">停止</button>
</div>
</template>
<script>
export default {
props: {
initialCountdown: {
type: Number,
required: true
}
},
data() {
return {
countdown: this.initialCountdown,
intervalId: null
};
},
computed: {
isCountdownRunning() {
return this.intervalId !== null;
}
},
methods: {
startCountdown() {
if (this.intervalId === null) {
this.intervalId = setInterval(() => {
if (this.countdown > 0) {
this.countdown -= 1;
} else {
this.stopCountdown();
}
}, 1000);
}
},
stopCountdown() {
if (this.intervalId !== null) {
clearInterval(this.intervalId);
this.intervalId = null;
}
}
},
mounted() {
this.startCountdown();
},
beforeUnmount() {
this.stopCountdown();
}
};
</script>
这个代码实例修复了原始代码中的问题,并提供了一个可以正常运行的倒计时组件。它使用了Vue 3的生命周期钩子和计算属性来管理状态,并确保了组件在不需要时能正确地清理计时器。
评论已关闭