js / vue 实现倒计时
方法一:js实现
html:读取相应的变量
js:声明变量,调用定时器前先判断好是否已经超过时间,如果没有超过则开始计时器 调用函数,当倒计时到最后一秒时,清除定时器。
计算时分秒的时候要用Math.floor()往下取整,否则容易产生一秒跳两秒的情况。当达到期限时要清除定时器。
实现效果如图:
代码如下:
counted () {
const endDate = new Date("2021-02-06T19:20:00").getTime()
const nowDate = new Date().getTime()
if(endDate > nowDate) {
this.countdown = setInterval(() => {
this.computedCountDown()
},1000)
} else {
clearInterval(this.countdown)
this.countdown = ''
}
},
computedCountDown () {
const endDate = new Date("2021-02-06T19:20:00").getTime()
const nowDate = new Date().getTime()
const leftTime = parseInt((endDate - nowDate) / 1000)
this.day = Math.floor(leftTime / ( 60 * 60 * 24 )) > 9 ? Math.floor(leftTime / ( 60 * 60 * 24 )) : '0' + Math.floor(leftTime / ( 60 * 60 * 24 ))
this.hour = Math.floor(leftTime / ( 60 * 60 ) % 24) > 9 ? Math.floor(leftTime / ( 60 * 60 ) % 24) : '0' + Math.floor(leftTime / ( 60 * 60 ) % 24)
this.minute = Math.floor(leftTime / ( 60 ) % ( 60 )) > 9 ? Math.floor(leftTime / ( 60 ) % ( 60 )) : '0' + Math.floor(leftTime / ( 60 ) % ( 60 ))
this.seconds = Math.floor(leftTime % ( 60 )) > 9 ? Math.floor(leftTime % ( 60 )) : '0' + Math.floor(leftTime % ( 60 ))
if (nowDate >= endDate) {
clearInterval(this.countdown)
this.countdown = ''
}
}
方法二:vue实现
html:
js:
watch监听器
methods:
实现效果如图;
代码如下:
created () {
this.computeLeftTime()
this.countDown = setInterval(() => {
this.computeLeftTime()
}, 1000)
},
watch: {
$route: {
handler: function (value) {
if (value.params.id) {
this.computeLeftTime()
this.countDown = setInterval(() => {
this.computeLeftTime()
}, 1000)
} else {
clearInterval(this.countDown)
this.countDown = ''
}
},
deep: true
},
}
methods: {
computeLeftTime () { // 计算倒计时
const endDate = new Date(new Date(期限时间))
const nowDate = new Date()
if (期限时间 && new Date(期限时间) <= new Date()) {
clearInterval(this.countDown)
// 更新项目状态
this.$emit('reflash')
} else {
const totalSeconds = parseInt((endDate - nowDate) / 1000)
// 天数
this.leftDay = Math.floor(totalSeconds / (60 * 60 * 24))
// 取模(余数)
var modulo = totalSeconds % (60 * 60 * 24)
// 小时数
this.leftHour = Math.floor(modulo / (60 * 60)) > 9 ? Math.floor(modulo / (60 * 60)) : '0' + Math.floor(modulo / (60 * 60)).toString()
modulo = modulo % (60 * 60)
// 分钟
this.leftMinute = Math.floor(modulo / 60) > 9 ? Math.floor(modulo / 60) : '0' + Math.floor(modulo / 60).toString()
// 秒
this.leftSecond = modulo % 60 > 9 ? modulo % 60 : '0' + (modulo % 60).toString()
}
},
}