<div class="countDownContent">
<div class="timeTitle">双12大促限时优惠:</div>
<div class="countDownBox">
<div class="timeBox">{{ minutes }}</div>
:
<div class="timeBox">{{ seconds }}</div>
:
<div class="timeBox">{{ milliseconds }}</div>
</div>
</div>
data(){
return {
// 倒计时
totalMilliseconds: 5 * 60 * 1000, // 5分钟转换成毫秒
timer: null,
isRunning: false,
}
}
computed: {
minutes() {
const time = this.totalMilliseconds / 1000;
return Math.floor(time / 60)
.toString()
.padStart(2, "0");
},
seconds() {
const time = this.totalMilliseconds / 1000;
return Math.floor(time % 60)
.toString()
.padStart(2, "0");
},
milliseconds() {
return Math.floor((this.totalMilliseconds % 1000) / 10)
.toString()
.padStart(2, "0");
},
},
methods:{
// 倒计时
startTimer() {
if (!this.isRunning) {
this.isRunning = true;
this.timer = setInterval(() => {
if (this.totalMilliseconds > 0) {
this.totalMilliseconds -= 10; // 每10毫秒减少一次
} else {
this.resetTimer();
}
}, 10);
}
},
resetTimer() {
clearInterval(this.timer);
this.totalMilliseconds = 0; // 倒计时清0
this.isRunning = false;
// this.startTimer(); // 重置后立即开始新的计时
},
}
//生命周期 - 挂载完成(可以访问DOM元素)
mounted() {
this.startTimer(); // 页面加载完成后启动计时器
},
//生命周期 - 销毁之前
beforeDestroy() {
clearInterval(this.timer); // 清除计时器,防止内存泄漏
},