vue实现123456
Vue 实现数字递增动画
在 Vue 中实现数字从 1 递增到 123456 的动画效果,可以通过以下方法实现:
方法一:使用 transition 和计算属性
<template>
<div>
<transition name="count-up">
<span>{{ animatedNumber }}</span>
</transition>
</div>
</template>
<script>
export default {
data() {
return {
targetNumber: 123456,
currentNumber: 0
}
},
computed: {
animatedNumber() {
return Math.floor(this.currentNumber)
}
},
mounted() {
const duration = 2000 // 动画持续时间(毫秒)
const startTime = performance.now()
const animate = (timestamp) => {
const elapsed = timestamp - startTime
const progress = Math.min(elapsed / duration, 1)
this.currentNumber = progress * this.targetNumber
if (progress < 1) {
requestAnimationFrame(animate)
}
}
requestAnimationFrame(animate)
}
}
</script>
<style>
.count-up-enter-active, .count-up-leave-active {
transition: all 1s ease;
}
</style>
方法二:使用第三方库 vue-countup
安装依赖:

npm install vue-countup
实现代码:
<template>
<count-up
:startVal="0"
:endVal="123456"
:duration="2"
/>
</template>
<script>
import CountUp from 'vue-countup'
export default {
components: { CountUp }
}
</script>
方法三:纯 CSS 动画(适用于简单场景)

<template>
<div class="count-up">{{ animatedNumber }}</div>
</template>
<script>
export default {
data() {
return {
animatedNumber: 0
}
},
mounted() {
const increment = 123456 / 60 // 假设60帧完成
const interval = setInterval(() => {
this.animatedNumber += increment
if (this.animatedNumber >= 123456) {
this.animatedNumber = 123456
clearInterval(interval)
}
}, 16) // 约60fps
}
}
</script>
<style>
.count-up {
font-size: 24px;
font-weight: bold;
transition: all 2s ease-out;
}
</style>
性能优化建议
对于大数字动画,建议使用 requestAnimationFrame 而不是 setInterval,因为它能提供更平滑的动画效果并减少性能消耗。
可以添加缓动函数使动画更自然:
function easeOutQuad(t) {
return t * (2 - t)
}
然后在动画计算中使用:
this.currentNumber = easeOutQuad(progress) * this.targetNumber






