一、gsap实现
1. 安装且引入gsap
npm install gsap
import gsap from "gsap"

2. 页面中添加计步器用来改变数值(也可以用按钮),添加h2用来展示数字改变的动画效果
<div>
<input type="number" step="100" v-model="counter">
<h2>当前计数:{{ showNumber.toFixed(0) }}</h2>
</div>

3. 在data里定义两个数值
data() {
return {
counter: 0, // 初始
showNumber: 0, // 承接
}
},

4. 在watch里面监听要改变的原始数值
watch: {
counter(newValue, oldValue) {
gsap.to(this, { duration: 0.5, showNumber: newValue })
}
},

二、Vue动画实现
tip:建议使用gsap。
1. 页面中添加计步器用来改变数值(也可以用按钮),添加h2用来展示数字改变的动画效果

2. 在data里定义三个数值

3. 在watch里面监听要改变的原始数值并添加动画
watch: {
counter(newValue, oldValue) {
let startTime = null;
const animate = (timestamp) => {
console.log("timestamp", timestamp);
if (!startTime) startTime = timestamp;
const progress = timestamp - startTime;
// 根据动画进度计算数字的变化值
this.showNumber = Math.floor(oldValue + (progress / this.animationDuration * 100));
if (progress < this.animationDuration) {
// 继续执行动画
requestAnimationFrame(animate);
}
};
// 开始执行动画
requestAnimationFrame(animate);
}
},

