Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

vue 数字滚动组件

作者:浪子无家   发布日期:2025-08-04   浏览:64

<template>
  <div class="number-scroll">
    <span v-for="(digit, index) in digits" :key="index">{{ digit }}</span>
  </div>
</template>

<script>
export default {
  props: {
    value: {
      type: Number,
      required: true
    },
    duration: {
      type: Number,
      default: 2000 // 滚动动画的持续时间,默认为2秒
    }
  },
  data() {
    return {
      currentNumber: 0,
      intervalId: null
    };
  },
  computed: {
    digits() {
      return String(Math.floor(this.currentNumber)).padStart(3, '0').split('');
    }
  },
  watch: {
    value(newVal) {
      this.startScrolling(newVal);
    }
  },
  mounted() {
    this.startScrolling(this.value);
  },
  methods: {
    startScrolling(target) {
      clearInterval(this.intervalId);
      let start = this.currentNumber;
      let startTime = null;

      const animate = (timestamp) => {
        if (!startTime) startTime = timestamp;
        const progress = timestamp - startTime;
        this.currentNumber = easeInOutQuad(progress, start, target - start, this.duration);
        if (progress < this.duration) {
          this.intervalId = requestAnimationFrame(animate);
        }
      };

      requestAnimationFrame(animate);
    }
  }
};

// 缓动函数,用于实现平滑滚动效果
function easeInOutQuad(t, b, c, d) {
  t /= d / 2;
  if (t < 1) return c / 2 * t * t + b;
  t--;
  return -c / 2 * (t * (t - 2) - 1) + b;
}
</script>

<style scoped>
.number-scroll {
  font-size: 2em;
  font-weight: bold;
}

.number-scroll span {
  display: inline-block;
  margin-right: 5px;
}
</style>

解释说明

  1. 模板部分 (<template>):

    • 使用 v-for 循环渲染每个数字字符。
    • digits 是一个计算属性,将当前数字转换为字符串并填充到三位数(例如:001),然后拆分为单个字符。
  2. 脚本部分 (<script>):

    • 接受两个属性 valueduration,分别表示目标数字和动画持续时间。
    • currentNumber 用于存储当前显示的数字。
    • digits 计算属性将 currentNumber 转换为三位数的数组形式。
    • startScrolling 方法启动滚动动画,使用 requestAnimationFrame 实现平滑过渡。
    • easeInOutQuad 是一个缓动函数,用于创建平滑的滚动效果。
  3. 样式部分 (<style scoped>):

    • 设置数字的字体大小和样式。
    • 每个数字字符之间有一定的间距。

上一篇:vue前端和后端怎么连接起来

下一篇:vue.global.js

大家都在看

vue.config.js configu

node.js vue

vue 图表组件

vue3watch监听多个变量

vue查看版本

vue3 reactive对象重新赋值

vue等待几秒

vue3 setup computed

vue screenfull

vue json.stringify

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站