vue实现数字效果
Vue 实现数字动画效果
在 Vue 中实现数字动画效果通常涉及数字的递增、滚动或变化动画。以下是几种常见实现方式:
使用第三方库(如 vue-count-to)
安装 vue-count-to 库:

npm install vue-count-to
在组件中使用:
<template>
<count-to :start-val="0" :end-val="1000" :duration="3000"></count-to>
</template>
<script>
import CountTo from 'vue-count-to'
export default {
components: { CountTo }
}
</script>
自定义数字动画(纯 Vue 实现)
通过计算属性和定时器实现:

<template>
<div>{{ animatedNumber }}</div>
</template>
<script>
export default {
data() {
return {
startVal: 0,
endVal: 1000,
duration: 2000,
currentVal: 0
}
},
computed: {
animatedNumber() {
return Math.floor(this.currentVal)
}
},
mounted() {
const startTime = Date.now()
const updateValue = () => {
const elapsed = Date.now() - startTime
const progress = Math.min(elapsed / this.duration, 1)
this.currentVal = this.startVal + progress * (this.endVal - this.startVal)
if (progress < 1) {
requestAnimationFrame(updateValue)
}
}
updateValue()
}
}
</script>
数字格式化(添加千分位)
结合动画和数字格式化:
<template>
<div>{{ formattedNumber }}</div>
</template>
<script>
export default {
data() {
return { currentVal: 0 }
},
computed: {
formattedNumber() {
return this.currentVal.toLocaleString()
}
},
methods: {
animateNumber(endVal, duration) {
let startTimestamp = null
const step = (timestamp) => {
if (!startTimestamp) startTimestamp = timestamp
const progress = Math.min((timestamp - startTimestamp) / duration, 1)
this.currentVal = Math.floor(progress * endVal)
if (progress < 1) {
window.requestAnimationFrame(step)
}
}
window.requestAnimationFrame(step)
}
},
mounted() {
this.animateNumber(1000000, 2000)
}
}
</script>
数字滚动效果(类似计数器)
实现数字逐个滚动的视觉效果:
<template>
<div class="counter">
<span v-for="(digit, index) in digits" :key="index" class="digit">
{{ digit }}
</span>
</div>
</template>
<script>
export default {
props: ['value'],
data() {
return { currentValue: 0 }
},
computed: {
digits() {
return String(this.currentValue).split('')
}
},
watch: {
value(newVal) {
this.animateTo(newVal)
}
},
methods: {
animateTo(target) {
const duration = 1000
const start = this.currentValue
const increment = (target - start) / (duration / 16)
const update = () => {
this.currentValue += increment
if ((increment > 0 && this.currentValue < target) ||
(increment < 0 && this.currentValue > target)) {
requestAnimationFrame(update)
} else {
this.currentValue = target
}
}
update()
}
},
mounted() {
this.currentValue = this.value
}
}
</script>
<style>
.digit {
display: inline-block;
transition: transform 0.3s ease;
}
.digit:hover {
transform: translateY(-10px);
}
</style>
注意事项
- 性能优化:对于频繁更新的数字,使用
requestAnimationFrame而非setInterval - 数字格式化:使用
toLocaleString()实现本地化数字显示 - 组件销毁时:清除动画帧请求避免内存泄漏
- 移动端兼容:测试触摸设备上的动画流畅度
以上方法可根据具体需求选择实现,第三方库适合快速开发,自定义实现则提供更多灵活性。





