項目中需要用到倒計時的功能,封裝了一個組件。
代碼解讀:
- 1:created周期中獲取傳入參數時間的剩余秒數: this.initSecondsLeft() 並綁定間隔事件 intervalEvent
- 2: 在computed屬性中刷新當前剩余時間的結果
- 3: 結束后觸發父組件的handle-done事件,父組件做出對應操作,如彈窗或信息提示
<template>
<div>
<div style="text-align:center;color:red;">
<h2>{{showTimeLeft}}</h2>
</div>
<div style="text-align:center;color:green;">
<h2>{{showTimeLeft}}</h2>
</div>
</div>
</template>
<script>
export default {
name: "timeCountDown",
props: {
endDate: String,
},
data() {
return {
timeLeft: 0,
bundleIntervalEvent: ""
};
},
computed: {
//用計算屬性顯示結果
showTimeLeft() {
//剩余秒數<=0
if (this.timeLeft <= 0) {
// 結束event
this.$emit('handle-done', true)
return "已過期";
}
// 剩余秒數>0
else {
let day = Math.floor(this.timeLeft / 86400);
let hour = Math.floor((this.timeLeft % 86400) / 3600);
let min = Math.floor(((this.timeLeft % 86400) % 3600) / 60);
let sec = Math.floor(((this.timeLeft % 86400) % 3600) % 60);
return (day + "天 " + (hour < 10 ? "0" : "") + hour + ": " + (min < 10 ? "0" : "") + min + ": " + (sec < 10 ? "0" : "") + sec
);
}
}
},
methods: {
//和當前日期比較,計算剩余多少秒
initSecondsLeft() {
let currentDate = new Date();
let tmp = this.endDate.split(/[- : /]/);
let toEndDate = new Date(tmp[0], tmp[1] - 1, tmp[2], tmp[3], tmp[4], tmp[5]);
//參數日期 > 當前日期 => 獲取剩余秒數
if (toEndDate > currentDate) {
this.timeLeft = Math.floor((toEndDate.getTime() - currentDate.getTime()) / 1000);
} else {
this.timeLeft = 0;
}
},
//間隔事件: 剩余秒數--, 當剩余秒數為0時,清除間隔事件.
intervalEvent() {
if (this.timeLeft > 0) {
this.timeLeft--;
} else {
clearInterval(this.bundleIntervalEvent);
}
},
},
mounted() {
},
created() {
//初始化剩余秒數
this.initSecondsLeft();
//執行間隔事件.
this.bundleIntervalEvent = setInterval(this.intervalEvent, 1000);
},
beforeDestroy() {
clearInterval(this.bundleIntervalEvent);
}
};
</script>