1、使用 vue-count-to 插件
- 安装插件
npm install vue-count-to
- 在项目中引入并使用插件
// main.js
import Vue from 'vue';
import App from './App.vue';
import CountTo from 'vue-count-to';
Vue.component('count-to', CountTo);
new Vue({
render: h => h(App),
}).$mount('#app');
- 在组件中使用 count-to
<template>
<div>
<count-to :start-val="0" :end-val="2021" suffix="条" :duration="2000"></count-to>
</div>
</template>
<script>
export default {
name: 'App',
};
</script>
<style>
/* 你的样式 */
</style>
参数选项
【注意】:当autoplay:true时,它将在startVal或endVal更改时自动启动
2、自定义数字渐变组件
如果你不想使用第三方插件,可以自己编写一个简单的数字渐变组件。以下是一个示例:
- 创建 CountTo.vue 组件
<template>
<span>{{ count }}</span>
</template>
<script>
export default {
props: {
startVal: {
type: Number,
default: 0
},
endVal: {
type: Number,
required: true
},
duration: {
type: Number,
default: 1000
}
},
data() {
return {
count: this.startVal
};
},
mounted() {
this.startCount();
},
methods: {
startCount() {
const startTime = Date.now();
const endTime = startTime + this.duration;
const range = this.endVal - this.startVal;
const stepTime = Math.abs((this.duration / range) || 10);
let self = this;
const timer = setInterval(() => {
const now = Date.now();
const remaining = endTime - now;
if (remaining > 0) {
const count = this.endVal - (remaining * range) / this.duration;
self.count = Math.round(count);
} else {
self.count = this.endVal;
clearInterval(timer);
}
}, stepTime);
}
}
};
</script>
<style scoped>
/* 你的样式 */
</style>
- 在主组件中使用 CountTo 组件
<template>
<div>
<count-to :start-val="0" :end-val="2021" :duration="2000"></count-to>
</div>
</template>
<script>
import CountTo from './components/CountTo.vue';
export default {
name: 'App',
components: {
CountTo
}
};
</script>
<style>
/* 你的样式 */
</style>