vue 实现数字跳动
数字跳动动画实现方法
在Vue中实现数字跳动效果,可以通过以下几种方式:
使用transition组件结合CSS动画
通过Vue的transition组件配合CSS transition或animation实现基础动画效果:
<template>
<transition name="count-up">
<span :key="currentNumber">{{ currentNumber }}</span>
</transition>
</template>
<style>
.count-up-enter-active, .count-up-leave-active {
transition: all 0.5s ease;
}
.count-up-enter, .count-up-leave-to {
transform: translateY(-20px);
opacity: 0;
}
</style>
使用第三方库
安装专用数字动画库如vue-countup或countup.js:
npm install countup.js
<template>
<div ref="countup"></div>
</template>
<script>
import { CountUp } from 'countup.js';
export default {
props: ['endVal'],
mounted() {
this.animateNumber();
},
methods: {
animateNumber() {
new CountUp(this.$refs.countup, this.endVal, {
duration: 2,
separator: ','
}).start();
}
}
}
</script>
自定义数字递增函数
实现自定义的数字递增动画效果:
<template>
<span>{{ animatedNumber }}</span>
</template>
<script>
export default {
props: ['number'],
data() {
return {
animatedNumber: 0
}
},
watch: {
number(newVal) {
this.animateValue(this.animatedNumber, newVal, 1000);
}
},
methods: {
animateValue(start, end, duration) {
const startTime = performance.now();
const step = (timestamp) => {
const progress = Math.min((timestamp - startTime) / duration, 1);
this.animatedNumber = Math.floor(progress * (end - start) + start);
if (progress < 1) {
window.requestAnimationFrame(step);
}
};
window.requestAnimationFrame(step);
}
}
}
</script>
使用GSAP动画库
通过GSAP实现更流畅的数字动画效果:
<template>
<span ref="number">{{ targetNumber }}</span>
</template>
<script>
import gsap from 'gsap';
export default {
props: ['value'],
data() {
return {
targetNumber: 0
}
},
watch: {
value(newVal) {
gsap.to(this, {
duration: 1,
targetNumber: newVal,
onUpdate: () => {
this.$refs.number.textContent = Math.floor(this.targetNumber);
}
});
}
}
}
</script>
性能优化建议
对于大量数字动画场景,考虑使用requestAnimationFrame而非setInterval确保动画流畅性。避免在每次数字变化时触发DOM更新,可以使用虚拟DOM优化或防抖技术减少渲染次数。
数字格式化可在动画完成后进行,避免在动画过程中执行复杂的数字格式化计算影响性能。







