网站建设和维护待遇,良乡网站建设公司,大连网站制作公司费用多少,食品网站建设实施方案vue3封装数值动态递增组件前言源码举个例子#xff1a;前言
1#xff09;使用技术#xff1a; vue3.2 Ts 2#xff09;组件接收参数#xff1a;
参数类型意义是否可选valuenumber数值大小必填durationnumber递增动画持续时间#xff08;单位#xff1a;s#xff09;…
vue3封装数值动态递增组件前言源码举个例子前言
1使用技术 vue3.2 Ts 2组件接收参数
参数类型意义是否可选valuenumber数值大小必填durationnumber递增动画持续时间单位s可选默认为2isDecimalboolean是否显示为小数可选默认为false
3补充 组件本身没有过多样式想实现不同样式可以在调用组件时自定义设置样式
源码
templatedivspan refnumberDom0/span/div
/templatescript setup langts
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 refany(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 0let start: number 0let flag: boolean falsetimer setInterval(() {start stepif (start props.value) {flag props.isDecimalclearInterval(timer!)start props.valuetimer null}current startif (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)
}
/scriptstyle scoped
div {display: inline-block;
}
/style举个例子
1使用代码
templatedivNumericalIncrement :duration2 :is-decimaltrue :valueval classnum/NumericalIncrement/div
/templatescript setup langts
import NumericalIncrement from ./components/NumericalIncrement.vue
import {ref,onMounted} from vue;
const val ref(110)
onMounted((){setTimeout((){val.value200},3000)
})
/scriptstyle scoped
.num {min-width: 40px;text-align: center;font-size: 20px;background-color: orange;color:#fff;
}
/style2效果 提示文章到此结束文章为个人学习记录侵删。