很多大屏、官网或者展示类页面会用到数字跳动更新效果的需求,countup用起来就非常方便
一、官网
二、效果图
三、安装countup与引入
npm install countup 进行安装依赖
import { CountUp } from 'countUp.js';//需要用到的页面引入,也可以全局引入
四、具体封装代码
<template>
<span ref="countup"></span>
</template>
<script>
import { CountUp } from "countup.js";
export default {
name: "base-countup",
data() {
return {};
},
//父组件传值给子组件
props: {
start: {
type: Number,
default: 0,
},
end: {
type: Number,
default: 0,
},
decimals: {
type: Number,
default: 0,
},
duration: {
type: Number,
default: 2,
},
options: {
type: Object,
default() {
return {};
},
required: false,
},
},
watch: {
end() {
this.initCountUp();
},
},
mounted() {
// this.initCountUp();
this.$nextTick(() => {
// 使用 $nextTick 确保 DOM 更新完成
this.initCountUp();
});
},
methods: {
initCountUp() {
//配置数字滚动组件相关参数
const options = {
start: this.start,
duration: this.duration,
decimalPlaces: this.decimals, //保留两位小数
};
const numAnim = new CountUp(this.$refs.countup, this.end, options);
numAnim.start();// 启动 start函数支持传入一个回调函数作为参数
},
},
};
</script>
父组件相关代码
//使用前先引入子组件
<base-countup class="font-28 m-r5" :start="0" :end="285" :decimals="2"></base-countup>