Vueuse 实现数字滚动 Count-to

1,356 阅读1分钟

recording

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

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

vueuse 确实是个宝藏库,在此强烈推荐。

npm i @vueuse/core

组件具有3 个参数:

  • num: 显示的数字
  • duration: 动画持续时间,默认 1000
  • precision: 数字精度,默认 0
<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/…

原文地址 mp.weixin.qq.com/s/Duhitv-vu…