vue3+TS实现数字滚动递增效果
2021-07-13 14:45:38
优化了一下程序,在之前的思路上进行了改进,不需要用户定义每次增加数字多少,用户只需要定义总时长,和每次更新的时间。 每次增加数=(开始-结束)/次数, 而次数来自:总时长/更新时间。上代码:
<template> <span>{{ printVal }}</span> </template> <script lang='ts'> import { defineComponent } from 'vue' export default defineComponent({ props: { startVal: { type: Number, default: 0 }, endVal: { type: Number, default: null }, totalTime: { // 总时长 type: Number, default: 5000 }, refreshTime: { type: Number, default: 100 }, decimals: { // 是否是小数 type: Number, default: 0 } }, data() { return { start: +this.startVal, end: +this.endVal, formatSpeed: (this.endVal - this.startVal) / (this.totalTime / this.refreshTime) // 每次增加数=增加数/次数 } }, computed: { formatDecimals(): number { // 是否整数 const formatDecimals = (this as any).decimals > 0 ? (this as any).decimals : 0 return formatDecimals }, printVal() { // 保留几位小数 const start = (this as any).start.toFixed(this.formatDecimals) return start } }, methods: { accumulativeMachine() { setInterval(() => { this.start += this.formatSpeed if (this.startVal < this.endVal) { if (this.printVal >= this.end) { this.start = this.end } } else { if (this.printVal <= this.end) { this.start = this.end } } }, this.refreshTime) } }, mounted() { this.$nextTick(() => { this.accumulativeMachine() }) } }) </script>
而且这里还判断了是从小到大还是从大到小。不需要用户自己手动去定义,程序自行判断。
调用方法
<NumberGrow :startVal="2000" :endVal='item.id'/>