<template>
<div>
<div>【单个秒杀】组件</div>
<div>{
{countDownList}}</div>
</div>
</template>
<script>
export default {
components: {
},
props: {},
data() {
return {
countDownList: '00天00时00分00秒', //初始化时间
actEndTime: '2022-08-18 02:19:00' //设置结束时间
};
},
watch: {},
computed: {},
created() {
this.countDown(); //一进入页面,就调用秒杀倒计时函数
},
methods: {
timeFormat(param) {
//(三元表达式)传入一个值,如果小于10,就在前面加0,如果大于0,就直接显示 传入9 ,返回09 传入30 返回30
return param < 10 ? '0' + param : param;
},
//设置秒杀倒计时函数
countDown(it) {
var interval = setInterval(() => { //(1)定时器
let newTime = new Date().getTime();// (2)获取当前时间,同时得到活动结束时间数组
let endTime = new Date(this.actEndTime).getTime(); // (3)对结束时间进行处理渲染到页面
let obj = null; //(4)设置一个新的数组
if (endTime - newTime > 0) { // (5)如果活动未结束,对时间进行处理
let time = (endTime - newTime) / 1000;
// 获取天、时、分、秒
let day = parseInt(time / (60 * 60 * 24));
let hou = parseInt(time % (60 * 60 * 24) / 3600);
let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
obj = {
day: this.timeFormat(day),
hour: this.timeFormat(hou),
min: this.timeFormat(min),
sec: this.timeFormat(sec)
};
} else { // 秒杀活动已结束,全部设置为'00',默认值
obj = {
day: '00',
hour: '00',
min: '00',
sec: '00'
};
clearInterval(interval); //(7)清除定时器
}
this.countDownList = obj.day + '天' + obj.hour + '时' + obj.min + '分' + obj.sec + '秒'; //(8)拼接字符串
}, 1000);
}
},
}
</script>
<style lang="scss" scoped>
</style>
効果は次のとおりです。