vue实现数字跳动
实现数字跳动效果
在Vue中实现数字跳动效果,可以通过CSS动画或JavaScript动画库来完成。以下是几种常见的实现方式:
使用CSS过渡动画
通过Vue的transition组件结合CSS过渡实现数字变化时的动画效果:
<template>
<div>
<transition name="fade">
<span :key="currentNumber">{{ currentNumber }}</span>
</transition>
<button @click="changeNumber">改变数字</button>
</div>
</template>
<script>
export default {
data() {
return {
currentNumber: 0
}
},
methods: {
changeNumber() {
this.currentNumber = Math.floor(Math.random() * 100)
}
}
}
</script>
<style>
.fade-enter-active, .fade-leave-active {
transition: all 0.5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
transform: translateY(20px);
}
</style>
使用GSAP动画库
GSAP是一个强大的JavaScript动画库,可以实现更复杂的数字跳动效果:
<template>
<div>
<div ref="numberElement">{{ animatedNumber }}</div>
<button @click="animateTo(100)">跳动到100</button>
</div>
</template>
<script>
import { gsap } from 'gsap'
export default {
data() {
return {
animatedNumber: 0
}
},
methods: {
animateTo(target) {
gsap.to(this, {
duration: 1,
animatedNumber: target,
ease: "bounce.out"
})
}
}
}
</script>
自定义数字递增动画
实现一个自定义的数字递增动画,模拟计数器的效果:

<template>
<div>
<div>{{ formattedNumber }}</div>
<button @click="startAnimation(0, 1000)">开始动画</button>
</div>
</template>
<script>
export default {
data() {
return {
currentNumber: 0,
animationFrame: null
}
},
computed: {
formattedNumber() {
return Math.floor(this.currentNumber)
}
},
methods: {
startAnimation(start, end) {
const duration = 2000 // 2秒
const startTime = performance.now()
const animate = (timestamp) => {
const elapsed = timestamp - startTime
const progress = Math.min(elapsed / duration, 1)
this.currentNumber = start + (end - start) * progress
if (progress < 1) {
this.animationFrame = requestAnimationFrame(animate)
}
}
cancelAnimationFrame(this.animationFrame)
this.animationFrame = requestAnimationFrame(animate)
}
},
beforeDestroy() {
cancelAnimationFrame(this.animationFrame)
}
}
</script>
使用vue-count-to插件
对于更简单的实现,可以使用专门为Vue设计的数字动画插件vue-count-to:
-
首先安装插件:

npm install vue-count-to -
在组件中使用:
<template> <div> <count-to :start-val="0" :end-val="100" :duration="3000"></count-to> </div> </template>
export default { components: { CountTo } }
```数字格式化与千分位
在数字跳动的同时添加千分位格式化:
<template>
<div>
<div>{{ formattedNumber }}</div>
<button @click="animateNumber(0, 1234567)">开始动画</button>
</div>
</template>
<script>
export default {
data() {
return {
currentNumber: 0
}
},
computed: {
formattedNumber() {
return this.currentNumber.toLocaleString()
}
},
methods: {
animateNumber(start, end) {
const duration = 2000
let startTimestamp = null
const step = (timestamp) => {
if (!startTimestamp) startTimestamp = timestamp
const progress = Math.min((timestamp - startTimestamp) / duration, 1)
this.currentNumber = Math.floor(progress * (end - start) + start)
if (progress < 1) {
window.requestAnimationFrame(step)
}
}
window.requestAnimationFrame(step)
}
}
}
</script>
以上方法提供了从简单到复杂的数字跳动实现方案,可以根据项目需求选择适合的方式。CSS过渡适合简单的数字变化,GSAP适合需要复杂缓动效果的场景,自定义实现则提供了最大的灵活性。






