vue3 数字滚动插件 countup.js

vue yekong 958℃

数字滚动效果

vue3 数字滚动插件 countup.js

动画效果

在Vue.js中,可以使用countUp.js插件实现数字滚动。这是一个独立的,能让你创建动态递增或递减的数字动画的JavaScript库。

首先,你需要在项目中安装这个库:

npm install countup.js --save

然后,在你的组件中引入并使用它:

<template>
  <div>
    <span ref="countUp">{{value}}</span>
  </div>
</template>

<script>
import { CountUp } from 'countup.js';

export default {
  data() {
    return {
      value: 0,
    };
  },
  watch: {
    value(newValue, oldValue) {
      const countUp = new CountUp(this.$refs.countUp, newValue, {
        startVal: oldValue,
        duration: 1.5,
      });
      if (!countUp.error) {
        countUp.start();
      } else {
        console.error(countUp.error);
      }
    },
  },
  mounted() {
    this.value = 100; // 测试数字滚动动画
  },
};
</script>

在上面的代码中,当value的值变化时,我们创建了一个新的CountUp实例,并以旧值为起点,新值为终点进行滚动动画。如果有错误发生,我们将在控制台中打印错误信息。

注意,在这个例子中,我们在mounted()钩子函数中将value设置为100,以便在组件挂载时可以看到滚动动画效果。你可能需要根据你的实际需求来调整这个值。

封装

<template>
  <div>
    <span ref="countUp">{{ num }}</span>
  </div>
</template>

<script>
import {CountUp} from 'countup.js';

export default {
  data() {
    return {
    };
  },
  props: {
    num: {
      type: [Number, String],
      default() {
        return 0;
      }
    }
  },
  watch: {
    num(newValue, oldValue) {
      const countUp = new CountUp(this.$refs.countUp, newValue, {
        startVal: oldValue,
        duration: 1.5,
      });
      if (!countUp.error) {
        countUp.start();
      } else {
        console.error(countUp.error);
      }
    },
  },
  mounted() {
  },
};
</script>

使用

引入组件

import countUp from "./countUp.vue";
  components: {
    countUp,
  },

<countUp :num="item.value"></countUp>
喜欢 (1)