昨天在做dashboard界面时,发现有些比较敏感的数字需要一些花里胡哨的特效才能显得高大上,这不得整个数字累加的效果上去?
安装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的选项