vue3封装数值动态递增组件
- 前言
- 源码
- 举个例子:
前言
1)使用技术:
vue3.2 + Ts
2)组件接收参数:
参数 | 类型 | 意义 | 是否可选 |
---|---|---|---|
value | number | 数值大小 | 必填 |
duration | number | 递增动画持续时间(单位:s) | 可选,默认为2 |
isDecimal | boolean | 是否显示为小数 | 可选,默认为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)效果
提示:文章到此结束,文章为个人学习记录,侵删。