手写简化vue-count-to组件实现数字动画过渡

175 阅读1分钟

话不多说直接上代码

<template>
<span>{{ currentCount }}</span>
</template> 
<script> 
export default {
    props: { 
        end: { type: Number, required: true },
        duration: { type: Number, default: 2000 }, 
        startOnMount: { type: Boolean, default: true } 
        }, 
    data() {
        return { 
        currentCount: 0, 
        intervalId: null
        }; 
       }, 
    mounted() { 
        if (this.startOnMount) { 
            this.startCount(); 
            } 
           }, 
    methods: { 
    startCount() {
        const increment = Math.ceil(this.end / (this.duration / 10));
        this.intervalId = setInterval(() => {
                                    if (this.currentCount < this.end) {
                                    this.currentCount += increment; 
                                    } else {
                                      this.currentCount = this.end;   
                                      clearInterval(this.intervalId); 
                                      }
                                    }, 10); 
                                  } 
                 } 
              };
 </script>

这个组件需要接收三个参数 end: 结束数值,必须传入 duration: 动画结束时间,已毫秒为单位,这里设置为2000,可以自行设置 startOnMount: 是否在挂载阶段开始动画,默认为true

组件会在mounted钩子函数中开始动画没如果startOnMount属性为false,则需要通过调用startCount方法手动开始动画,

父组件调用,记得导入和注册组件

count-to.png

导入count-to.png

注册count-to组件.png