新建组件CountUp.vue
javascript
<template>
<div>{{ thousandthPercentile?count.toLocaleString('en-US'):count }}</div>
</template>
<script>
export default {
name: "CountUp",
props: {
start: {
type: Number,
default: 0,//开始值
},
end: {
type: Number,
default: 100,//结束值
},
stepTime: {
type: Number,
default: 10,//切换时间间隔
},
duration: {
type: Number,
default: 2000,//持续时间
},
thousandthPercentile: {
type: Boolean,
default: false,//是否使用千位分隔符
}
},
data() {
return {
count: this.start,
timer: null,
};
},
watch:{
end:{
handler(val){
// console.log('目标值',val)
this.animateCountUp()
}
},
},
mounted() {
// console.log('目标值',this.end)
this.animateCountUp();
},
methods: {
animateCountUp() {
// console.log('参数',this.end,this.duration)
if(this.timer){
clearInterval(this.timer);
}
const start = this.start;//起始值
const end = this.end;//结束值
const duration = this.duration;//持续时间间隔
const stepTime = this.stepTime;//切换时间
const range = end - start;
let current = start;
// let increment = parseInt(range / (duration / stepTime));
let increment = range / (duration / stepTime);
this.timer = setInterval(() => {
current += increment;
// console.log('加载',this.count,range,duration,stepTime,increment)
if (current >= end) {
this.count = end;
clearInterval(this.timer);
} else {
this.count = parseInt(current);
}
}, stepTime);
},
},
};
</script>
使用该组件
javascript
<template>
<CountUp class="item_count" :end="count" :thousandthPercentile="true"></CountUp>
</template>
<script>
import CountUp from "./CountUp"
export default {
name: "ActualInformation",
components:{ CountUp },
data(){
return{
count:9999
}
}
}
</script>
<style>
.item_count{
font-family: "ChePaiZiTi";
font-size: 26px;
font-weight: bold;
text-align: left;
color: #00FFAA;
margin-right: 3px;
}
</style>