vue2实现数字渐变加载的效果

1、使用 vue-count-to 插件

  • 安装插件
npm install vue-count-to
  • 在项目中引入并使用插件
// main.js
import Vue from 'vue';
import App from './App.vue';
import CountTo from 'vue-count-to';

Vue.component('count-to', CountTo);

new Vue({
  render: h => h(App),
}).$mount('#app');
  • 在组件中使用 count-to
<template>
  <div>
    <count-to :start-val="0" :end-val="2021" suffix="" :duration="2000"></count-to>
  </div>
</template>

<script>
export default {
  name: 'App',
};
</script>

<style>
/* 你的样式 */
</style>

参数选项

在这里插入图片描述【注意】:当autoplay:true时,它将在startVal或endVal更改时自动启动
在这里插入图片描述

2、自定义数字渐变组件

如果你不想使用第三方插件,可以自己编写一个简单的数字渐变组件。以下是一个示例:

  • 创建 CountTo.vue 组件
<template>
  <span>{{ count }}</span>
</template>

<script>
export default {
  props: {
    startVal: {
      type: Number,
      default: 0
    },
    endVal: {
      type: Number,
      required: true
    },
    duration: {
      type: Number,
      default: 1000
    }
  },
  data() {
    return {
      count: this.startVal
    };
  },
  mounted() {
    this.startCount();
  },
  methods: {
    startCount() {
      const startTime = Date.now();
      const endTime = startTime + this.duration;
      const range = this.endVal - this.startVal;
      const stepTime = Math.abs((this.duration / range) || 10);

      let self = this;
      const timer = setInterval(() => {
        const now = Date.now();
        const remaining = endTime - now;
        if (remaining > 0) {
          const count = this.endVal - (remaining * range) / this.duration;
          self.count = Math.round(count);
        } else {
          self.count = this.endVal;
          clearInterval(timer);
        }
      }, stepTime);
    }
  }
};
</script>

<style scoped>
/* 你的样式 */
</style>
  • 在主组件中使用 CountTo 组件
<template>
  <div>
    <count-to :start-val="0" :end-val="2021" :duration="2000"></count-to>
  </div>
</template>

<script>
import CountTo from './components/CountTo.vue';

export default {
  name: 'App',
  components: {
    CountTo
  }
};
</script>

<style>
/* 你的样式 */
</style>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值