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

数字滚动效果,在后台管理系统的 dashboard 页面基本就是标配。

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

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

useTransition 文档地址:https://vueuse.org/core/useTransition/#usetransition

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

MoCountTo 使用

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

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地址:https://github.com/lucidity99/mocha-vue3-system

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

原文始发于微信公众号(自由前端之路):从零开始Vue3+Element Plus后台管理系统(25) 使用 Vueuse 实现数字滚动 Count-to

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/291645.html

(0)
葫芦侠五楼的头像葫芦侠五楼

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!