<template>
<span>{{ currentCount }}</span>
</template>
<script>
export default {
props: {
end: { type: Number, required: true },
duration: { type: Number, default: 2000 },
startOnMount: { type: Boolean, default: true }
},
data() {
return {
currentCount: 0,
intervalId: null
};
},
mounted() {
if (this.startOnMount) {
this.startCount();
}
},
methods: {
startCount() {
const increment = Math.ceil(this.end / (this.duration / 10));
this.intervalId = setInterval(() => {
if (this.currentCount < this.end) {
this.currentCount += increment;
} else {
this.currentCount = this.end;
clearInterval(this.intervalId);
}
}, 10);
}
}
};
</script>
这个组件需要接收三个参数 end
: 结束数值,必须传入 duration
: 动画结束时间,已毫秒为单位,这里设置为2000,可以自行设置 startOnMount
: 是否在挂载阶段开始动画,默认为true
组件会在mounted钩子函数中开始动画没如果startOnMount
属性为false,则需要通过调用startCount
方法手动开始动画,
父组件调用,记得导入和注册组件
这个导入路径根据你自己设置的路径来,我这里是导入下的包
使用