Blame view

ant-design-vue-jeecg/src/components/CountDown/CountDown.vue 2 KB
肖超群 authored
1
2
3
4
5
6
7
8
<template>
  <span>
    {{ lastTime | format }}
  </span>
</template>

<script>
肖超群 authored
9
10
11
function fixedZero(val) {
  return val * 1 < 10 ? `0${val}` : val;
}
肖超群 authored
12
肖超群 authored
13
14
15
16
17
18
export default {
  name: "CountDown",
  props: {
    format: {
      type: Function,
      default: undefined
肖超群 authored
19
    },
肖超群 authored
20
21
22
    target: {
      type: [Date, Number],
      required: true,
肖超群 authored
23
    },
肖超群 authored
24
25
26
    onEnd: {
      type: Function,
      default: () => {
肖超群 authored
27
      }
肖超群 authored
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
    }
  },
  data() {
    return {
      dateTime: '0',
      originTargetTime: 0,
      lastTime: 0,
      timer: 0,
      interval: 1000
    }
  },
  filters: {
    format(time) {
      const hours = 60 * 60 * 1000;
      const minutes = 60 * 1000;

      const h = Math.floor(time / hours);
      const m = Math.floor((time - h * hours) / minutes);
      const s = Math.floor((time - h * hours - m * minutes) / 1000);
      return `${fixedZero(h)}:${fixedZero(m)}:${fixedZero(s)}`
    }
  },
  created() {
    this.initTime()
    this.tick()
  },
  methods: {
    initTime() {
      let lastTime = 0;
      let targetTime = 0;
      this.originTargetTime = this.target
      try {
        if (Object.prototype.toString.call(this.target) === '[object Date]') {
          targetTime = this.target
        } else {
          targetTime = new Date(this.target).getTime()
肖超群 authored
64
        }
肖超群 authored
65
66
67
      } catch (e) {
        throw new Error('invalid target prop')
      }
肖超群 authored
68
肖超群 authored
69
      lastTime = targetTime - new Date().getTime();
肖超群 authored
70
肖超群 authored
71
72
73
74
      this.lastTime = lastTime < 0 ? 0 : lastTime
    },
    tick() {
      const {onEnd} = this
肖超群 authored
75
肖超群 authored
76
77
78
79
80
81
      this.timer = setTimeout(() => {
        if (this.lastTime < this.interval) {
          clearTimeout(this.timer)
          this.lastTime = 0
          if (typeof onEnd === 'function') {
            onEnd();
肖超群 authored
82
          }
肖超群 authored
83
84
85
86
87
88
89
90
91
92
        } else {
          this.lastTime -= this.interval
          this.tick()
        }
      }, this.interval)
    }
  },
  beforeUpdate() {
    if (this.originTargetTime !== this.target) {
      this.initTime()
肖超群 authored
93
    }
肖超群 authored
94
95
96
  },
  beforeDestroy() {
    clearTimeout(this.timer)
肖超群 authored
97
  }
肖超群 authored
98
}
肖超群 authored
99
100
101
102
103
</script>

<style scoped>

</style>