<div class="time_ing">
<p class="active_text">
当日已累计消费:{{ state }}
</p>
<div class="active_time">
<p>距离当日结束还剩</p>
<span>{{countdown.hours}}</span> :
<span>{{ countdown.minutes }}</span> :
<span>{{ countdown.seconds }}</span>
</div>
</div>
data () {
return {
countdown:{},//定时器的时间
intervalId:'',// 声明变量保存定时器 ID
}
}
beforeDestroy() {
this.clearInterval(); // 清除所有定时器
},
methods: {
//-----倒计时 开始------
async onlogding() {
let that = this;
// 清除旧的定时器
this.clearInterval();
const endTime = moment().format('YYYY-MM-DD 23:59:59'); // 获取当天结束时间
// 更新倒计时函数
const updateCountdown = () => {
const nowTime = moment().format('YYYY-MM-DD HH:mm:ss'); // 获取当前时间
let endTimeMoment = moment(endTime, 'YYYY-MM-DD HH:mm:ss');
let nowTimeMoment = moment(nowTime, 'YYYY-MM-DD HH:mm:ss');
const duration = moment.duration(endTimeMoment.diff(nowTimeMoment)); // 剩余时间差
let hours = Math.floor(duration.asHours());
let minutes = duration.minutes();
let seconds = duration.seconds();
// 将小时、分钟和秒数格式化为两位数,并以 : 分隔
hours = ("0" + hours).slice(-2);
minutes = ("0" + minutes).slice(-2);
seconds = ("0" + seconds).slice(-2);
that.countdown = { hours, minutes, seconds };
// console.log(that.countdown,'时间')
if (hours <= 0 && minutes <= 0 && seconds <= 0) {
that.clearInterval(); // 时间结束,停止倒计时
} else {
duration.subtract(1, 's'); // 每秒减少1秒
}
};
updateCountdown(); // 首次调用更新倒计时函数
// 每秒调用一次更新倒计时函数
that.intervalId = setInterval(updateCountdown, 1000);
},
clearInterval() {
clearInterval(this.intervalId);
},
//------倒计时 结束--------
}