digital scroll animation

Method 1: handwritten JS method

/* 数字滚动动画 */
numScroll(startNum, maxNum) {
  const that = this;
  let numText = startNum;
  let animateFrame; // 清除 requestAnimationFrame 请求动画帧
  // 数字动画
  function digitalAnimation() {
    numText += 5; // 速度的计算可以为小数 。数字越大,滚动越快
    if (numText >= maxNum) {
      numText = maxNum;
      cancelAnimationFrame(animateFrame);
    } else {
      animateFrame = requestAnimationFrame(digitalAnimation); // 请求动画帧(一个浏览器的宏任务)
    }
    that.amount = numText;
  }
  digitalAnimation(); // 数字动画
}

full code

<template>
  <div>
    <div @click="numScroll(0, 520)">滚动</div>
    <div>{
   
   { amount }}</div>
  </div>
</template>

<script>
  export default {
  data() {
    return {
      amount: 0,
    };
  },
  methods: {
    /* 数字滚动动画 */
    numScroll(startNum, maxNum) {
      const that = this;
      let numText = startNum;
      let animateFrame; // 清除 requestAnimationFrame 请求动画帧
      // 数字动画
      function digitalAnimation() {
        numText += 5; // 速度的计算可以为小数 。数字越大,滚动越快
        if (numText >= maxNum) {
          numText = maxNum;
          cancelAnimationFrame(animateFrame);
        } else {
          animateFrame = requestAnimationFrame(digitalAnimation); // 请求动画帧(一个浏览器的宏任务)
        }
        that.amount = numText;
      }
      digitalAnimation(); // 数字动画
    }
  }
};
</script>

<style scoped></style>

Method 2: Use the vue-count-to plugin

vue-count-to is a lightweight vue component without dependencies, which can override EasingFn by itself. You can set startVal and endVal, it will automatically judge the count for digital rendering.

npm install vue-count-to
<template>
  <div>
    <CountTo :startVal="startVal" :endVal="endVal" :duration="duration" />
  </div>
</template>

<script>
import CountTo from "vue-count-to";

export default {
  components: { CountTo },
  data() {
    return {
      startVal: 0, // 开始值
      endVal: 100, // 开始值
      duration: 3000, // 持续时间(毫秒为单位)
      timer: null // 定时器
    };
  },
  mounted() {
    this.timer = setInterval(() => {
      this.endVal = this.endVal * 2;
    }, 4000);
  },
  destroyed() {
    clearInterval(this.timer);
  }
};
</script>

<style scoped></style>

Parameter options:

Attributes describe type default
startVal start value Number 0
thanVal end value Number 2017
duration duration in milliseconds Number 3000
autoplay Autoplay Boolean true
decimals number of decimal places to display Number 0
decimal decimal division String .
separator delimiter String ,
prefix prefix String ""
suffix suffix String ""
useEasing Use easing Boolean true
easingFn easing callback Function

Note: When autoplay: true, it will start automatically when startVal or endVal changes

function name describe
mountedCallback Return callback after mount
start start counting
pause pause count
reset resetcountTo

Guess you like

Origin blog.csdn.net/AdminGuan/article/details/130207564