从零开始Vue3+Element Plus后台管理系统(25) 使用 Vueuse 实现数字滚动 Count-to

1,289 阅读1分钟

数字滚动效果,在 dashboard 页面基本就是标配。

一年前,写了篇文章,# 入门GSAP动画——一个简单的数字滚动动画,GSAP 实现很简单,但是拿这么个强大的库来做这点小事,实在有点高射炮打蚊子——大材小用。

element-plus的 Statistic 统计组件也有数字滚动的效果,其实就是用vueuse的useTransition

useTransition地址:vueuse.org/core/useTra…

MoCountTo 组件使用

3 个参数:

  • num: 显示的数字
  • duration: 动画持续时间
  • precision: 数字精度
<MoCountTo :num="198" />
<MoCountTo :num="198" :duration="2000" :precision="2" />

MoCountTo 组件代码

组件代码很简单,如下:

<template>
  <span> {{ formattedOutputValue }}</span>
</template>

<script setup lang="ts">
import { ref, watch, nextTick, computed } from 'vue'
import { useTransition } from '@vueuse/core'

interface Props {
  num: number
  duration?: number
  precision?: number // 数字精度
}

const props = defineProps<Props>()
const source = ref(0)
let outputValue = useTransition(source, {
  duration: props.duration || 1000
})

const precision = ref(
  props.precision !== undefined && Number.isInteger(props.precision) ? props.precision : 0
)
const formattedOutputValue = computed(() => outputValue.value.toFixed(precision.value))

watch(
  () => props.num,
  async (newVal) => {
    if (Number.isNaN(newVal)) {
      console.warn('Invalid number provided, defaulting to 0.')
      newVal = 0
    }

    await nextTick()
    source.value = newVal
  },
  { immediate: true }
)
</script>

项目地址

本项目GIT地址:github.com/lucidity99/…

如果有帮助,给个star ✨ 点个赞