count-down.vue
1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<template>
<div class="count-down-wrapper" v-if="countDown !== ''">
<i v-if="isShowIcon" class="time-icon"></i>
<span>{{ countDown }}</span>
</div>
</template>
<script>
export default {
props: {
leftTime: {
type: Number,
default: 0
},
isShowIcon: {
type: Boolean,
default: true
}
},
data() {
return {
remainTime: this.$props.leftTime,
countDown: "",
timeoutId: null
};
},
mounted() {
this.countDown = this.formatTime().join(":");
this.timeoutId = setInterval(() => {
this.remainTime--;
this.countDown = this.formatTime().join(":");
}, 1000);
},
destroyed() {
clearInterval(this.timeoutId);
},
watch: {
countDown(val) {
if (val === "") {
clearInterval(this.timeoutId);
}
}
},
methods: {
formatTime() {
if (this.remainTime <= 0) {
return [];
}
let remainTime = this.remainTime;
const hourInSecond = 60 * 60;
const numberOfHours = Math.floor(this.remainTime / hourInSecond);
remainTime = remainTime - numberOfHours * hourInSecond;
const numberOfMinutes = Math.floor(remainTime / 60);
const numberOfSeconds = remainTime - numberOfMinutes * 60;
return [numberOfHours, numberOfMinutes, numberOfSeconds].map(time => {
return time < 10 ? `0${time}` : `${time}`;
});
}
}
};
</script>
<style lang="scss" scoped>
.count-down-wrapper {
display: flex;
font-size: 32px;
font-weight: bold;
align-items: center;
& > i {
width: 30px;
height: 30px;
display: block;
background: url("~statics/image/order/time-icon@3x.png");
background-size: contain;
background-position: center;
}
& > span {
padding: 0 9px;
@include num
}
}
</style>