template部分
<ul>
<li>
<div class="item">{{day}}</div>
<div class="name">Days</div>
</li>
<li>
<div class="item">{{hour}}</div>
<div class="name">Hours</div>
</li>
<li>
<div class="item">{{min}}</div>
<div class="name">Minutes</div>
</li>
<li>
<div class="item">{{second}}</div>
<div class="name">Seconds</div>
</li>
</ul>
scss样式
ul{
width: 5rem;
margin: auto;
display: flex;
justify-content: space-between;
padding-left: 0.38rem;
li{
width: 0.9rem;
color: #fff;
text-align: center;
.item{
width: 0.9rem;
height: 0.8rem;
background-image: linear-gradient(to right, #D8D8D8 , #ABEBFF);
font-size: 0.48rem;
text-align: center;
line-height: 0.8rem;
font-weight: 600;
}
.name{
font-size: 0.2rem;
padding-top: 0.15rem;
}
}
}
js部分
<script>
export default {
data () {
return {
curStartTime: '2022-03-16 08:00:00',
day: '00',
hour: '00',
min: '00',
second: '00',
}
},
mounted(){
this.curStartTime = '2022-03-20'
this.countTime()
},
methods:{
// 倒计时
countTime () {
// 获取当前时间
let date = new Date()
let now = date.getTime()
// 设置截止时间
let endDate = new Date(this.curStartTime) // this.curStartTime需要倒计时的日期
let end = endDate.getTime()
// 时间差
let leftTime = end - now
// 定义变量 d,h,m,s保存倒计时的时间
if (leftTime >= 0) {
// 天
let day = Math.floor(leftTime / 1000 / 60 / 60 / 24)
// 三元表达式判断不满10前面加0
this.day = day < 10 ? '0' + day : day
// 时
let h = Math.floor(leftTime / 1000 / 60 / 60 % 24)
this.hour = h < 10 ? '0' + h : h
// 分
let m = Math.floor(leftTime / 1000 / 60 % 60)
this.min = m < 10 ? '0' + m : m
// 秒
let s = Math.floor(leftTime / 1000 % 60)
this.second = s < 10 ? '0' + s : s
} else {
this.day = 00
this.hour = '00'
this.min = '00'
this.second = '00'
}
// 等于0的时候不调用
if (Number(this.hour) === 0 && Number(this.day) === 0 && Number(this.min) === 0 && Number(this.second) === 0) {
return
} else {
// 递归每秒调用countTime方法,显示动态时间效果,
setTimeout(this.countTime, 1000)
}
},
}
}
</script>