vue2 简单实现数字滚动特效,主要实现思路是,mounted 钩子函数中调用 animation 方法,实现数字滚动。
<template>
<p class="my-number-to">
<span><slot /></span><span ref="numberTo">0</span>
</p>
</template>
<script>
export default {
props: {
time: { type: Number, default: 3 }, // 每30ms增加的数值
value: { type: Number, default: 100 } // 值
},
mounted() {
this.animation(this.$refs.numberTo)
},
methods: {
/**
* @description 动画函数 - 数字滚动
*/
animation(ele) {
let step = this.value / (10 * this.time)
let initial = 0
let count = 0
let timer = setInterval(() => {
count += step
if (count > this.value) {
clearInterval(timer)
count = this.value
timer = null
}
const calcCount = Math.floor(count)
// 如果数值未发生变动直接 return
if (calcCount == initial) return
initial = calcCount
ele.innerHTML = initial
}, 50)
}
}
}
</script>
<style lang="scss" scoped>
.my-number-to {
transform: translateZ(0);
}
</style>