vue3封装数值动态递增组件

7 篇文章 0 订阅

vue3封装数值动态递增组件


前言

1)使用技术:

vue3.2 + Ts

2)组件接收参数:

参数类型意义是否可选
valuenumber数值大小必填
durationnumber递增动画持续时间(单位:s)可选,默认为2
isDecimalboolean是否显示为小数可选,默认为false

3)补充:
组件本身没有过多样式,想实现不同样式可以在调用组件时自定义设置样式

源码

<template>
    <div>
        <span ref="numberDom">0</span>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUpdate, onBeforeUnmount, withDefaults, defineProps } from 'vue';

/**
 * @param value 数值大小 
 * @param duration 递增动画持续时间;
 * @param isDecimal 是否显示为小数
 */
const props = withDefaults(defineProps<{
    value: number,
    duration: number,
    isDecimal: boolean

}>(), {
    duration: 2,
    isDecimal: false
})

let timer: number  | null = null
const timerDelay = 5
const numberDom = ref<any>(null)

onMounted(() => {
    numericalIncrement(numberDom.value)
})
onBeforeUpdate(() => {
    if (timer) {
        clearInterval(timer!)
        timer = null
    }
    numericalIncrement(numberDom.value)
})
onBeforeUnmount(() => {
    if (timer) {
        clearInterval(timer!)
        timer = null
    }
})

/**
 * @method
 * @param ele 数值对应的dom元素
 * @desc 数值递增动画
 */
const numericalIncrement = (ele: Element) => {
    const step = (props.value * timerDelay) / (props.duration * 1000)
    let current: number = 0
    let start: number = 0
    let flag: boolean = false
    timer = setInterval(() => {
        start += step
        if (start >= props.value) {
            flag = props.isDecimal
            clearInterval(timer!)
            start = props.value
            timer = null
        }
        current = start
        if (flag) {
            ele.innerHTML = current
                .toString()
                .replace(/(\d)(?=(?:\d{3}[+]?)+$)/g, '$1,')
        } else {
            ele.innerHTML = current
                .toFixed(0) 
                .toString()
                .replace(/(\d)(?=(?:\d{3}[+]?)+$)/g, '$1,')
        }
    }, timerDelay)
}
</script>

<style scoped>
div {
    display: inline-block;
}
</style>

举个例子:

1)使用代码

<template>
  <div>
    <NumericalIncrement :duration="2" :is-decimal="true" :value="val" class="num"></NumericalIncrement>
  </div>
</template>

<script setup lang="ts">
import NumericalIncrement from './components/NumericalIncrement.vue'
import {ref,onMounted} from 'vue';
const val = ref(110)
onMounted(()=>{
  setTimeout(()=>{
    val.value=200
  },3000)
})
</script>
 
<style scoped>
.num {
  min-width: 40px;
  text-align: center;
  font-size: 20px;
  background-color: orange;
  color:#fff;
}
</style>

2)效果在这里插入图片描述


提示:文章到此结束,文章为个人学习记录,侵删。
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值