vue实现数字效果
Vue 实现数字动画效果
在 Vue 中实现数字动画效果通常涉及数字递增、滚动或其他视觉变化。以下是几种常见实现方式:
使用 Vue Transition 和计算属性
通过 Vue 的过渡系统结合计算属性实现简单数字变化动画:
<template>
<transition name="fade">
<span :key="currentNumber">{{ animatedNumber }}</span>
</transition>
</template>
<script>
export default {
data() {
return {
currentNumber: 0,
targetNumber: 1000,
animationDuration: 2000
}
},
computed: {
animatedNumber() {
return Math.floor(this.currentNumber)
}
},
mounted() {
const startTime = performance.now()
const animate = (timestamp) => {
const elapsed = timestamp - startTime
const progress = Math.min(elapsed / this.animationDuration, 1)
this.currentNumber = progress * this.targetNumber
if (progress < 1) {
requestAnimationFrame(animate)
}
}
requestAnimationFrame(animate)
}
}
</script>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
使用第三方库(如 GSAP)
GSAP 提供更强大的动画控制能力:
<template>
<div ref="numberElement">0</div>
</template>
<script>
import { gsap } from 'gsap'
export default {
data() {
return {
targetNumber: 5000
}
},
mounted() {
gsap.to(this.$refs.numberElement, {
innerText: this.targetNumber,
duration: 2,
snap: { innerText: 1 },
ease: "power1.out"
})
}
}
</script>
使用 vue-count-to 插件
专门为 Vue 设计的数字动画组件:
-
安装插件:
npm install vue-count-to -
在组件中使用:
<template> <countTo :startVal="0" :endVal="2024" :duration="3000"></countTo> </template>
export default { components: { countTo } }
```实现数字滚动效果
创建数字逐个滚动的视觉效果:
<template>
<div class="rolling-number">
<span v-for="(digit, index) in digits" :key="index" class="digit">
{{ digit }}
</span>
</div>
</template>
<script>
export default {
props: {
value: { type: Number, default: 0 }
},
computed: {
digits() {
return String(this.value).split('')
}
}
}
</script>
<style>
.rolling-number {
display: inline-flex;
overflow: hidden;
}
.digit {
display: inline-block;
transition: transform 0.5s ease;
}
</style>
数字格式化与动画结合
结合数字格式化和动画效果:
<template>
<div>{{ formattedNumber }}</div>
</template>
<script>
export default {
data() {
return {
currentValue: 0,
targetValue: 1234567.89
}
},
computed: {
formattedNumber() {
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD'
}).format(this.currentValue)
}
},
mounted() {
const animate = () => {
if (this.currentValue < this.targetValue) {
this.currentValue += (this.targetValue - this.currentValue) * 0.1
requestAnimationFrame(animate)
} else {
this.currentValue = this.targetValue
}
}
animate()
}
}
</script>
每种方法适用于不同场景,可根据项目需求选择简单原生实现或功能更丰富的第三方解决方案。







