vue实现数字跳动
实现数字跳动效果
使用Vue实现数字跳动效果可以通过过渡动画或第三方库完成。以下是几种常见方法:
使用Vue过渡动画
通过Vue的过渡系统结合CSS动画实现基础数字跳动:
<template>
<div>
<transition name="bounce">
<span :key="currentNumber">{{ currentNumber }}</span>
</transition>
<button @click="increment">增加</button>
</div>
</template>
<script>
export default {
data() {
return {
currentNumber: 0
}
},
methods: {
increment() {
this.currentNumber += 1
}
}
}
</script>
<style>
.bounce-enter-active {
animation: bounce-in 0.5s;
}
.bounce-leave-active {
animation: bounce-in 0.5s reverse;
}
@keyframes bounce-in {
0% {
transform: scale(0.8);
opacity: 0;
}
50% {
transform: scale(1.2);
}
100% {
transform: scale(1);
opacity: 1;
}
}
</style>
使用Tween.js实现平滑过渡
通过Tween.js库实现数字平滑过渡动画:
<template>
<div>
<span>{{ animatedNumber.toFixed(0) }}</span>
<button @click="animateTo(100)">跳动到100</button>
</div>
</template>
<script>
import TWEEN from '@tweenjs/tween.js'
export default {
data() {
return {
animatedNumber: 0
}
},
mounted() {
this.animate()
},
methods: {
animateTo(newValue) {
new TWEEN.Tween({ number: this.animatedNumber })
.to({ number: newValue }, 1000)
.easing(TWEEN.Easing.Quadratic.Out)
.onUpdate(obj => {
this.animatedNumber = obj.number
})
.start()
},
animate() {
requestAnimationFrame(this.animate)
TWEEN.update()
}
}
}
</script>
使用vue-count-to插件
专门为Vue设计的数字动画组件:
<template>
<div>
<countTo :startVal="0" :endVal="targetValue" :duration="2000"></countTo>
<button @click="targetValue += 100">增加100</button>
</div>
</template>
<script>
import countTo from 'vue-count-to'
export default {
components: { countTo },
data() {
return {
targetValue: 0
}
}
}
</script>
自定义数字跳动组件
创建可复用的数字跳动组件:
<template>
<span>{{ displayValue }}</span>
</template>
<script>
export default {
props: {
value: {
type: Number,
required: true
},
duration: {
type: Number,
default: 1000
}
},
data() {
return {
displayValue: 0,
startTime: null,
startValue: 0
}
},
watch: {
value(newVal) {
this.startAnimation(newVal)
}
},
mounted() {
this.displayValue = this.value
},
methods: {
startAnimation(endValue) {
this.startValue = this.displayValue
this.startTime = null
const step = timestamp => {
if (!this.startTime) this.startTime = timestamp
const progress = Math.min((timestamp - this.startTime) / this.duration, 1)
this.displayValue = Math.floor(this.startValue + (endValue - this.startValue) * progress)
if (progress < 1) {
requestAnimationFrame(step)
}
}
requestAnimationFrame(step)
}
}
}
</script>
实现数字格式化
在数字跳动过程中添加格式化功能:

// 在组件方法中添加
formatNumber(num) {
return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")
}
以上方法可根据实际需求选择使用,从简单CSS动画到复杂的数字过渡效果均可实现。






