数字滚动是很常见的特效
在项目中可以随意使用,非常方便。
直接进入主题
父组件代码:
<template>
<roll-number number="56.89" toFixedBit="2"></roll-number>
</template>
<script>
import rollNumber from '@/components/common/rollNumber'
export default {
components: { rollNumber }
}
</script>
子组件代码:
<template>
<div :class="`rollNumber ${className}`" :style="numberStyle">{{showText}}</div>
</template>
<script>
export default {
props: {
//保留几位小数字
toFixedBit: {
type: [Number],
default: function () {
return 0
}
},
//传入的数字
number: {
type: [Number],
default: function () {
return 0
}
},
//数字的样式
numberStyle: {
type: [String, Object],
default: function () {
return ''
}
},
//数字变化时间
duringTime: {
type: [Number],
default: function () {
return 500
}
},
//每隔多少时间变化一次数字
intervalTime: {
type: [Number],
default: function () {
return 20
}
},
//类名
className: {
type: [String],
default: function () {
return ''
}
},
},
data: function () {
return {
presentTime: 0,
progress: 0,
showText: '',
timer: null
}
},
mounted: function () {
this.init()
},
methods: {
init: function () {
this.presentTime = 0
this.progress = 0
this.showText = ''
this.timer && clearInterval(this.timer)
this.timer = setInterval(() => {
this.presentTime = this.presentTime + this.intervalTime
let number = (this.presentTime / this.duringTime) * this.number
number = number.toFixed(parseInt(this.toFixedBit > 0? this.toFixedBit : 0))
this.showText = number
if (this.presentTime >= this.duringTime) {
clearInterval(this.timer)
}
}, this.intervalTime)
}
},
watch: {
number: function (newVal) {
this.init()
},
toFixedBit: function () {
this.init()
},
duringTime: function (newVal) {
this.init()
},
intervalTime: function (newVal) {
this.init()
},
},
beforeDestroy: function () {
this.timer && clearInterval(this.timer)
}
}
</script>
<style scoped>
.rollNumber {
display: inline-block;
}
</style>
结语
以上是我的分享,希望那个能够提供给码友一点点的帮助。