使用 Vue 2.5 實作「動畫化數字」元件

做法

建立一個 AppAnimatedNumber 元件,並接收 count 屬性。

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
<template>
<span
v-text="number.toLocaleString()"
/>
</template>

<script>
export default {
name: 'AppAnimatedNumber',
props: {
count: {
type: Number,
default: 0,
},
},
data() {
return {
interval: null,
number: 0,
};
},
created() {
this.number = this.count;
},
watch: {
count() {
clearInterval(this.interval);
if (this.count === this.number) {
return;
}
this.interval = setInterval(() => {
let change = (this.count - this.number) / 10;
change = change >= 0 ? Math.ceil(change) : Math.floor(change);
this.number += change;
}, 1000 * 0.1);
},
},
};
</script>