78 lines
1.9 KiB
Vue
78 lines
1.9 KiB
Vue
<template>
|
|
<div>
|
|
<template v-if="days"></template>
|
|
{{ days }}天 {{ hours }}时 {{ minutes }}分 {{ seconds }}秒
|
|
</div>
|
|
</template>
|
|
|
|
<script>
|
|
export default {
|
|
name: 'CountdownTimer',
|
|
props: {
|
|
expirePeriod: {
|
|
type: Number,
|
|
required: true,
|
|
},
|
|
},
|
|
data() {
|
|
return {
|
|
countdown: null, // 定时器
|
|
totalSeconds: this.expirePeriod, // 总秒数
|
|
days: 0,
|
|
hours: 0,
|
|
minutes: 0,
|
|
seconds: 0,
|
|
};
|
|
},
|
|
watch: {
|
|
// 当 expirePeriod 发生变化时,重置倒计时
|
|
expirePeriod(newVal) {
|
|
this.resetCountdown(newVal);
|
|
},
|
|
},
|
|
mounted() {
|
|
this.resetCountdown(this.expirePeriod);
|
|
this.startCountdown();
|
|
},
|
|
beforeDestroy() {
|
|
// 在组件销毁前清除定时器
|
|
clearInterval(this.countdown);
|
|
},
|
|
methods: {
|
|
// 重置倒计时
|
|
resetCountdown(seconds) {
|
|
this.totalSeconds = seconds;
|
|
this.updateTime();
|
|
},
|
|
// 启动倒计时
|
|
startCountdown() {
|
|
this.countdown = setInterval(() => {
|
|
if (this.totalSeconds > 0) {
|
|
this.totalSeconds--;
|
|
this.updateTime();
|
|
} else {
|
|
// 倒计时结束后的处理
|
|
clearInterval(this.countdown);
|
|
this.days = 0;
|
|
this.hours = 0;
|
|
this.minutes = 0;
|
|
this.seconds = 0;
|
|
}
|
|
}, 1000);
|
|
},
|
|
// 更新显示的时间
|
|
updateTime() {
|
|
this.days = Math.floor(this.totalSeconds / (60 * 60 * 24));
|
|
this.hours = Math.floor((this.totalSeconds % (60 * 60 * 24)) / (60 * 60));
|
|
this.minutes = Math.floor((this.totalSeconds % (60 * 60)) / 60);
|
|
this.seconds = this.totalSeconds % 60;
|
|
|
|
// 格式化显示为两位数
|
|
this.days = this.days.toString().padStart(2, '0');
|
|
this.hours = this.hours.toString().padStart(2, '0');
|
|
this.minutes = this.minutes.toString().padStart(2, '0');
|
|
this.seconds = this.seconds.toString().padStart(2, '0');
|
|
},
|
|
},
|
|
};
|
|
</script> |