你知道这些数字随着时间的推移而增加,并在之间计算所有小数字吗?好吧,如果你想自己做,你已经到达了正确的地方。
我们将假设您已经设置了一个基本的Vue项目,否则它是 相当容易。
安装
首先,让我们使用 Yarn 或 NPM 安装 tween.js。
1# Yarn
2$ yarn add @tweenjs/tween.js
3
4# NPM
5$ npm install @tweenjs/tween.js
使用
然后,让我们创建一个快速包装组件,以保持所有动画逻辑. 它不需要真正的风格化。
1[label AnimatedCounter.vue]
2<template>
3 <span class="tweened-number">{{ tweeningValue }}</span>
4</template>
5
6<script>
7export default {
8 props: {
9 // The value that we'll be tweening to.
10 value: {
11 type: Number,
12 required: true
13 },
14
15 // How long the tween should take. (In milliseconds.)
16 tweenDuration: {
17 type: Number,
18 default: 500
19 }
20 },
21
22 watch: {
23 // Whenever `props.value` changes, update the tween.
24 value(newVal, oldVal) {
25 this.tween(oldVal, newVal)
26 }
27 },
28
29 // This holds the temporary state of the tweened value.
30 data() {
31 return {
32 tweeningValue: 0
33 }
34 },
35
36 mounted() {
37 this.tween(0, this.value)
38 },
39
40 methods: {
41 // This is our main logic block. It handles tweening from a start value to an end value.
42 tween(start, end) {
43 let frameHandler
44
45 // Handles updating the tween on each frame.
46 const animate = function (currentTime) {
47 TWEEN.update(currentTime)
48 frameHandler = requestAnimationFrame(animate)
49 }
50
51 const myTween = new TWEEN.Tween({ tweeningValue: start })
52 .to({ tweeningValue: end }, this.tweenDuration)
53 // Be careful to not to do too much here! It will slow down the app.
54 .onUpdate(() => {
55 this.tweeningValue = myTween.tweeningValue.toFixed(0)
56 })
57 .onComplete(() => {
58 // Make sure to clean up after ourselves.
59 cancelAnimationFrame(frameHandler)
60 })
61 // This actually starts the tween.
62 .start()
63
64 frameHandler = requestAnimationFrame(animate)
65 }
66 }
67}
68</script>
现在我们可以这样使用这个组件:
1[label ExampleComponent.vue]
2<template>
3 <div>
4 <p>This number does move-y things. <animated-counter :value="myValue"></animated-counter></p>
5 <p>You can change the tweened number here: <input type="text" v-model="myValue"/></p>
6 <!-- It transitions like magic! Magic with a bunch of code behind it, that is. -->
7 </div>
8</template>
9<script>
10import AnimatedCounter from './AnimatedCounter.vue';
11
12export default {
13 components: {
14 AnimatedCounter
15 },
16
17 data() {
18 return {
19 myValue: 100
20 }
21 }
22}
23</script>
仅此而已! 借助其他几个库,您还可以切换其他值,例如字符串、数组或颜色。