<div id="app">{{ `${day}天 ${hr}小時 ${min}分鐘 ${sec}分鐘` }}</div>
new Vue({
el: '#app',
data: function () {
return {
day: 0, hr: 0, min: 0, sec: 0
}
},
mounted: function () {
this.countdown()
},
methods: {
countdown: function () {
const end = Date.parse(new Date('2017-12-01'))
const now = Date.parse(new Date())
const msec = end - now
let day = parseInt(msec / 1000 / 60 / 60 / 24)
let hr = parseInt(msec / 1000 / 60 / 60 % 24)
let min = parseInt(msec / 1000 / 60 % 60)
let sec = parseInt(msec / 1000 % 60)
this.day = day
this.hr = hr > 9 ? hr : '0' + hr
this.min = min > 9 ? min : '0' + min
this.sec = sec > 9 ? sec : '0' + sec
const that = this
setTimeout(function () {
that.countdown()
}, 1000)
}
}
})
function countdown () {
// 目標(biāo)日期時間戳
const end = Date.parse(new Date('2017-12-01'))
// 當(dāng)前時間戳
const now = Date.parse(new Date())
// 相差的毫秒數(shù)
const msec = end - now
// 計算時分秒數(shù)
let day = parseInt(msec / 1000 / 60 / 60 / 24)
let hr = parseInt(msec / 1000 / 60 / 60 % 24)
let min = parseInt(msec / 1000 / 60 % 60)
let sec = parseInt(msec / 1000 % 60)
// 個位數(shù)前補零
hr = hr > 9 ? hr : '0' + hr
min = min > 9 ? min : '0' + min
sec = sec > 9 ? sec : '0' + sec
// 控制臺打印
console.log(`${day}天 ${hr}小時 ${min}分鐘 ${sec}秒`)
// 一秒后遞歸
setTimeout(function () {
countdown()
}, 1000)
}