不使用第三方插件自己写一个数字递增滚动组件
开箱即用水贴专用哈哈哈
封装NumberRoller.vue组件
<template> <div> <span :style="fontColorSize">{{ formattedValue || 0 }}</span> </div> </template> <script> export default { props: { rollNumber: { // 最终值 type: String, default: "5.548", }, fontSpacing: { //刷新间隔,单位毫秒, 数字间距 >8 type: Number, default: 1, }, rollingSpeed: { // 动画时长,单位毫秒 type: Number, default: 1.5, }, fontColorSize: { //字体大小以及颜色 type: String, default: "", }, }, data() { return { startValue: 0, currentInterval: null, currentValue: 0, steps: 0, }; }, computed: { formattedValue() { return this.currentValue.toFixed(2); }, }, methods: { startAnimation() { this.steps = Math.ceil(this.rollingSpeed / this.fontSpacing); const diff = this.rollNumber - this.startValue; const stepValue = diff / this.steps; this.currentInterval = setInterval(() => { this.currentValue += stepValue; this.steps--; if (this.steps <= 0) { clearInterval(this.currentInterval); this.currentValue = this.rollNumber; } }, this.fontSpacing); }, }, mounted() { this.startAnimation(); }, }; </script> <style scoped> </style>
父组件需要向子组件传四个值,最终值、刷新间隔、动画时长、以及样式,总体来说,这个组件的原理是通过定时器和递增值的不断累加,以动画效果显示从起点到终点的数字递增过程。这样的实现方式是基于 JavaScript 的定时器和数字计算。
<NumberRoller :rollNumber="你的最终值" :rollingSpeed="2000" :fontSpacing="10" :fontColorSize="'font-size: 2.6429rem;color: #f8ec48;'" />
效果图:
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 百万级群聊的设计实践
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期