vue3+TS实现数字滚动增加

2021-07-13 10:52:25

首先申明,这个是我在网上扒的一个,功能是没有任何问题的,如果只是简单的网页呈现,是没有任何问题的。附上代码

<template>
  <span>{{ printVal }}</span>
</template>

<script lang='ts'>
import { defineComponent } from 'vue'
export default defineComponent({
  // <count-in :startVal='0' :endVal='100.525' :speed='800' :decimals="3" :isReverse=false />
  props: {
    startVal: {
      type: Number,
      default: null
    },
    endVal: {
      type: Number,
      default: null
    },
    speed: {
      type: Number,
      default: 5
    },
    decimals: { // 是否是小数
      type: Number,
      default: 0
    },
    isReverse: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      start: +this.startVal,
      end: +this.endVal,
      formatSpeed: +this.speed || 5
    }
  },
  computed: {
    formatDecimals(): number {
      // 是否整数
      const formatDecimals = (this as any).decimals > 0 ? (this as any).decimals : 0
      return formatDecimals
    },
    decimalsLen(): number {
      // 1 = 0.001 * decimalsLen(x);
      const decimalsLen = Math.pow(10, this.formatDecimals)
      return decimalsLen
    },
    printVal() {
      // 保留几位小数
      const start = (this as any).start.toFixed(this.formatDecimals)
      return start
    }
  },
  methods: {
    accumulativeMachine() {
      setTimeout(() => {
        if (this.isReverse) {
          const decimals = this.formatDecimals === 0 ? 0 : 1 / this.decimalsLen
          const formatSpeed = this.formatSpeed / this.decimalsLen + decimals
          this.start -= formatSpeed
          if (this.printVal <= this.end) {
            this.start = this.end
            return
          }
        } else {
          const decimals = this.formatDecimals === 0 ? 0 : 1 / this.decimalsLen
          const formatSpeed = this.formatSpeed / this.decimalsLen + decimals
          this.start += formatSpeed
          if (this.printVal >= this.end) {
            this.start = this.end
            return
          }
        }
        this.accumulativeMachine()
      }, 8)
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.accumulativeMachine()
    })
  }
})
</script>

<style>
.number-grow-warp {
  transform: translateZ(0);
}
</style>

使用方法

<NumberGrow :startVal='0' :endVal='100.525' :speed='5' :decimals="0" :isReverse="false" />

但是有一个小缺陷,因为代码里面指定了每次增加的数字,如果我这个数字非常大,百万千万。那这里滚动的时间就较长,这可能就和我的需求有点不相符了。如果找不到合适的,那只能自己写一个了。 后续我会附上代码

关于

联系方式 :

mail: hey_cool@163.com ,
QQ:583459700

备案许可证编号:蜀ICP备16005545号-1 © COPYRIGHT 2015-2024 zhmzjl.com | by: KAPO