範例舉例倒數一天
<div x-data="timer(new Date().setDate(new Date().getDate() + 1))" x-init="init();">
<span x-text="time().days"></span>:
<span x-text="time().hours"></span>:
<span x-text="time().minutes"></span>:
<span x-text="time().seconds"></span>
</div>
x-data裡執行timer()函式,
並傳入值new Date().setDate(new Date().getDate() + 1)
,也就是一天
而x-init執行init()函式,向下偷看一下,
裡面有setInterval()
,指定每1000毫秒會執行一次,setRemaining()
裡面計算還剩多少時間並轉為數字。
剩下的我們先看js吧。
function timer(expiry) {
return {
expiry: expiry,
remaining: null,
init() {
this.setRemaining()
setInterval(() => {
this.setRemaining();
}, 1000);
},
setRemaining() {
const diff = this.expiry - new Date().getTime();
this.remaining = parseInt(diff / 1000);
},
days() {
return {
value: this.remaining / 86400,
remaining: this.remaining % 86400
};
},
hours() {
return {
value: this.days().remaining / 3600,
remaining: this.days().remaining % 3600
};
},
minutes() {
return {
value: this.hours().remaining / 60,
remaining: this.hours().remaining % 60
};
},
seconds() {
return {
value: this.minutes().remaining,
};
},
format(value) {
return ("0" + parseInt(value)).slice(-2)
},
time() {
return {
days: this.format(this.days().value),
hours: this.format(this.hours().value),
minutes: this.format(this.minutes().value),
seconds: this.format(this.seconds().value),
}
},
}
}
裡面幾乎都用數學的角度去除,接著顯示餘數判斷剩多少時、分、秒,
最後統一轉換形式在一起顯示出來,
就可以做簡易的倒數計時了!