不使用第三方插件自己写一个数字递增滚动组件

发布时间 2023-12-25 17:51:09作者: 艾码的日常生活

开箱即用水贴专用哈哈哈
封装NumberRoller.vue组件

<template>
  <div>
    <span :style="fontColorSize">{{ formattedValue || 0 }}</span>
  </div>
</template>

<script>
export default {
  props: {
    rollNumber: {
      // 最终值
      type: String,
      default: "5.548",
    },
    fontSpacing: {
      //刷新间隔,单位毫秒, 数字间距 >8
      type: Number,
      default: 1,
    },
    rollingSpeed: {
      // 动画时长,单位毫秒
      type: Number,
      default: 1.5,
    },
    fontColorSize: {
      //字体大小以及颜色
      type: String,
      default: "",
    },
  },
  data() {
    return {
      startValue: 0,
      currentInterval: null,
      currentValue: 0,
      steps: 0,
    };
  },
  computed: {
    formattedValue() {
      return this.currentValue.toFixed(2);
    },
  },
  methods: {
    startAnimation() {
      this.steps = Math.ceil(this.rollingSpeed / this.fontSpacing);
      const diff = this.rollNumber - this.startValue;
      const stepValue = diff / this.steps;

      this.currentInterval = setInterval(() => {
        this.currentValue += stepValue;
        this.steps--;

        if (this.steps <= 0) {
          clearInterval(this.currentInterval);
          this.currentValue = this.rollNumber;
        }
      }, this.fontSpacing);
    },
  },
  mounted() {
    this.startAnimation();
  },
};
</script>

<style scoped>
</style>

父组件需要向子组件传四个值,最终值、刷新间隔、动画时长、以及样式,总体来说,这个组件的原理是通过定时器和递增值的不断累加,以动画效果显示从起点到终点的数字递增过程。这样的实现方式是基于 JavaScript 的定时器和数字计算。

     <NumberRoller
        :rollNumber="你的最终值"
        :rollingSpeed="2000"
        :fontSpacing="10"
        :fontColorSize="'font-size: 2.6429rem;color: #f8ec48;'"
     />

效果图: