基于vue的原生js数字滚动

//调用方式
  <CountTo :end-val="100" :decimals="2" :duration="1000"/>

//组件

<template>
  <span>
    {{currentVal.toFixed(this.decimals)}}
  </span>
</template>

<script>
  export default {
    name:'CountTo',
    props:{
      endVal:{
        type:Number,
        default:2021//结束值
      },
      decimals:{
        type:Number,
        default: 0//小数位数
      },
      duration:{
        type:Number,
        default: 1000//滚动持续时间
      }
    },
    watch:{
      endVal:{
        handler(){
          this.currentVal=0;
        },
        immediate:true
      }
    },
    computed:{
      interval(){
        return this.decimals>0?this.duration/(this.endVal*10^this.decimals):this.duration/this.endVal//每次增加单位值所需时间
      },
      limit(){
        return this.decimals>0?1/(10^this.decimals):1//每次增加值
      }
    },
    data () {
      return {
        timer:null,
        currentVal:0//当前值
      }
    },
    methods:{
      reset(){//重置为0
        this.currentVal=0
        if(this.timer){
          clearTimeout(this.timer)
          this.timer=null;
        }
      },
      start(){
        this.loop();
      },
      loop(){
        this.timer=setTimeout(()=>{//setTimeout最小间隔10毫秒,调整单位最小值及每10毫秒所需增加的值
          if(this.currentVal<this.endVal){
            this.currentVal+=+(this.limit*10/this.interval).toFixed(this.decimals);
          }
          this.loop()
        },10)

      },
    },
    mounted() {
      this.loop()
    },
    beforeDestroy() {
      if(this.timer){
        clearTimeout(this.timer)
      }
    }

  }
</script>

 

posted @ 2021-10-25 11:23  *朝晖  阅读(239)  评论(0编辑  收藏  举报