目的:每天中午12:00開始,動態顯示倒計時
export defalut {
name: ' ',
data () {
timeObj: {
h: null,
m: null,
s: null
},
leftCount: 0 //倒計時變量
},
methods:{
time(){
end = new Date(new Date().toLocaleDateString()).getTime() + 12 * 60 * 60 * 1000 //獲取每天凌晨時間戳加上12個小時的時間戳
now = new Date().getTime() //獲取當前時間戳
this.leftCount = end - now // 獲取倒計時時間戳
this.timeObj.h = Math.floor(this.leftCount / 1000 / 60 / 60 % 24) //獲取小時
this.timeObj.m = Math.floor(this.leftCount / 1000 / 60 % 60) //獲取分鍾
this.timeObj.s = Math.floor(this.leftCount / 1000 % 60) //獲取秒
if (this.leftCount <= 0) {
const endtwo = end + 24 * 60 * 60 * 1000 //這里是每天12:00的時間戳
this.leftCount = endtwo - now // 重新賦值一次是因為倒計時歸0時,leftCount是一個負值,而且倒計時時間變成了第二天的12:00,所以需要重新賦值一次leftCount
//這里其實可以單獨封裝成一個函數進行調用,跟上面的代碼一樣的,leftCount既然已經重新賦值了timeObj也要重新進行賦值
this.timeObj.h = Math.floor(this.leftCount / 1000 / 60 / 60 % 24) //獲取小時
this.timeObj.m = Math.floor(this.leftCount / 1000 / 60 % 60) //獲取分鍾
this.timeObj.s = Math.floor(this.leftCount / 1000 % 60) //獲取秒
}
},
openTime () { //倒計時:每一秒減一秒
setTiemout( () => {
leftCount -= 1000
}, 1000)
}
},
created () {
this.time()
this.openTime()
}
}
// 個位數前補零
// hour = hour > 9 ? hour : '0' + hour