vue 实现数字跳动
Vue 实现数字跳动效果
数字跳动效果可以通过 Vue 的过渡动画或第三方库实现。以下是几种常见方法:
使用 Vue Transition 和 CSS 动画
通过 Vue 的 <transition> 组件结合 CSS 动画实现数字平滑过渡。
<template>
<div>
<transition name="slide-up" mode="out-in">
<span :key="currentNumber">{{ currentNumber }}</span>
</transition>
</div>
</template>
<script>
export default {
data() {
return {
currentNumber: 0,
targetNumber: 100
};
},
mounted() {
this.animateNumber();
},
methods: {
animateNumber() {
const duration = 2000; // 动画持续时间(毫秒)
const startTime = Date.now();
const startValue = this.currentNumber;
const updateNumber = () => {
const elapsed = Date.now() - startTime;
const progress = Math.min(elapsed / duration, 1);
this.currentNumber = Math.floor(startValue + (this.targetNumber - startValue) * progress);
if (progress < 1) {
requestAnimationFrame(updateNumber);
}
};
requestAnimationFrame(updateNumber);
}
}
};
</script>
<style>
.slide-up-enter-active, .slide-up-leave-active {
transition: all 0.5s ease;
}
.slide-up-enter-from, .slide-up-leave-to {
opacity: 0;
transform: translateY(20px);
}
</style>
使用 GSAP 动画库
GSAP 提供了更强大的动画控制能力,适合复杂数字动画效果。
<template>
<div>
<span ref="numberElement">{{ currentNumber }}</span>
</div>
</template>
<script>
import { gsap } from 'gsap';
export default {
data() {
return {
currentNumber: 0
};
},
mounted() {
this.animateWithGSAP();
},
methods: {
animateWithGSAP() {
gsap.to(this, {
duration: 2,
currentNumber: 100,
onUpdate: () => {
this.currentNumber = Math.floor(this.currentNumber);
}
});
}
}
};
</script>
使用 vue-count-to 组件
专门为 Vue 设计的数字动画组件,简单易用。
安装:
npm install vue-count-to
使用:
<template>
<countTo :startVal="0" :endVal="100" :duration="2000"></countTo>
</template>
<script>
import countTo from 'vue-count-to';
export default {
components: { countTo }
};
</script>
自定义缓动函数
实现更自然的数字跳动效果,可以添加缓动函数。
easeOutQuad: function(t, b, c, d) {
return -c * (t /= d) * (t - 2) + b;
}
在动画更新时调用缓动函数计算当前值:
this.currentNumber = Math.floor(this.easeOutQuad(progress, startValue, endValue - startValue, 1));
以上方法可根据需求选择,Vue Transition 适合简单效果,GSAP 适合复杂动画,vue-count-to 则提供了开箱即用的解决方案。







