Vue3使用CountUp.js实现页面数字跳动

发布时间:2022-3-12 13:04

昨天在做dashboard界面时,发现有些比较敏感的数字需要一些花里胡哨的特效才能显得高大上,这不得整个数字累加的效果上去?

最开始想着用js自己撸一个,但是发现其实要做精致一点还是挺麻烦的,不如直接用插件来的实在,于是找到了countUp.js

安装countUp.js

npm i countup.js

最后发现官网只有一个vue2版本的案例,而且看起来也挺复杂,决定使用在vue3中调用一下它,写一个组件方便下一次使用。

代码如下:

<template>
  <span ref="count" />
</template>

<script>
import { CountUp } from 'countup.js'
const defaultOptions = {
  startVal: 0, // number to start at (0)
  decimalPlaces: 0, // number of decimal places (0)
  duration: 2, // animation duration in seconds (2)
  useGrouping: true, // example: 1,000 vs 1000 (true)
  useEasing: true, // ease animation (true)
  smartEasingThreshold: 999, // smooth easing for large numbers above this if useEasing (999)
  smartEasingAmount: 333, // amount to be eased for numbers above threshold (333)
  separator: ',', // grouping separator (',')
  decimal: '.' // decimal ('.')
  // easingFn: easing function for animation (easeOutExpo)
  // easingFn: (t: number, b: number, c: number, d: number) => number,
  // formattingFn: (n: number) => string, // this function formats result
  // prefix: string, // text prepended to result
  // suffix: string, // text appended to result
  // numerals: string[], // numeral glyph substitution
}
export default {
  name: 'CountUp',
  props: {
    // 起始值
    endVal: {
      type: Number,
      default: 0
    },
    options: {
      type: Object,
      default: () => {}
    }
  },
  watch: {
    endVal() {
      if (this.$refs.count) {
        this.initCountUp()
      }
    }
  },
  mounted() {
    this.initCountUp()
  },
  methods: {
    initCountUp() {
      const coutOptions = Object.assign({}, defaultOptions, this.options)
      const countUp = new CountUp(this.$refs.count, this.endVal, coutOptions)
      countUp.start()
    }
  }
}
</script>

跟vue2好像没啥区别... 不管了反正挺好用的

使用也很简单

<count-up :end-val="title"/>

共两个参数:endVal和options,options的参数具体参照官网的options的选项

Vue PostCSS的使用介绍 网站建设

Vue PostCSS的使用介绍

postcss 一种对css编译的工具,类似babel对js的处理,常见的功能如: 1 . 使用下一代css语法 2 . 自动补全浏览器前缀 3 . 自动把px代为转换成rem ...
Vue package.json配置深入分析 网站建设

Vue package.json配置深入分析

package.json是每个前端项目都会有的json文件,位于项目的根目录中。很多脚手架在创建项目的时候会帮我们自动初始化好 package.json。package.json有许多配置与项目息息相...