summaryrefslogtreecommitdiffstats
path: root/src/components/CountUp.vue
blob: 3bd01075905ba05d52d6916b7d244618d5f17d07 (plain)
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
<template>
    <span v-if="isNum" ref="output">{{ outputFixed }}</span> <span v-if="isNum">{{ unit }}</span>
    <span v-else>{{ value }}</span>
</template>

<script lang="ts">

import { sleep } from "../util.ts";

export default {

    props: {
        /** Value to count */
        value: {
            type: [ String, Number ],
            default: 0,
        },
        time: {
            type: Number,
            default: 0.3,
        },
        /** Unit of the value */
        unit: {
            type: String,
            default: "ms",
        },
    },

    data() {
        return {
            output: "",
            frameDuration: 30,
        };
    },

    computed: {
        isNum() {
            return typeof this.value === "number";
        },
        outputFixed() {
            if (typeof this.output === "number") {
                if (this.output < 1) {
                    return "<1";
                } else if (Number.isInteger(this.output)) {
                    return this.output;
                } else {
                    return this.output.toFixed(2);
                }
            } else {
                return this.output;
            }
        }
    },

    watch: {
        async value(from, to) {
            let diff = to - from;
            let frames = 12;
            let step = Math.floor(diff / frames);

            if (! (isNaN(step) || ! this.isNum || (diff > 0 && step < 1) || (diff < 0 && step > 1) || diff === 0)) {
                for (let i = 1; i < frames; i++) {
                    this.output += step;
                    await sleep(15);
                }
            }

            this.output = this.value;
        },
    },

    mounted() {
        this.output = this.value;
    },

    methods: {},

};
</script>