Vue3基于countUp.js實(shí)現(xiàn)數(shù)字滾動(dòng)的插件
countUp 簡介
CountUp.js 是一種無依賴項(xiàng)的輕量級(jí) JavaScript 類,可用于快速創(chuàng)建以更有趣的方式顯示數(shù)字?jǐn)?shù)據(jù)的動(dòng)畫。CountUp 可以在兩個(gè)方向上進(jìn)行計(jì)數(shù),具體取決于傳遞的開始和結(jié)束值。
雖然現(xiàn)在市面上基于 countUp.js 二次封裝的Vue組件不在少數(shù), 但我個(gè)人是不太喜歡使用這些第三方封裝的,因?yàn)榈谌浇M件的更新頻率很難保證,也許作者只是一時(shí)興起封裝上傳了, 并未打算繼續(xù)維護(hù),如果使用了 等于后續(xù)根本沒有維護(hù)性了, 所以這種二次封裝我推薦自行實(shí)現(xiàn), 我們可以通過本次封裝熟悉一下 vue3, ts 的語法
countUp 組件封裝
首先進(jìn)行安裝
npm i countup.js
安裝好之后新建文件 CountUp.vue , template部分很簡單, 只需要一個(gè)span標(biāo)簽, 同時(shí)給span一個(gè) ref='countupRef' 就完成了,首先引入 countup.js, 按住Ctrl鼠標(biāo)左鍵點(diǎn)擊Countup.js可以看到 d.ts文件, countUp.d.ts 如下
export interface CountUpOptions {
startVal?: number;
decimalPlaces?: number;
duration?: number;
useGrouping?: boolean;
useIndianSeparators?: boolean;
useEasing?: boolean;
smartEasingThreshold?: number;
smartEasingAmount?: number;
separator?: string;
decimal?: string;
easingFn?: (t: number, b: number, c: number, d: number) => number;
formattingFn?: (n: number) => string;
prefix?: string;
suffix?: string;
numerals?: string[];
enableScrollSpy?: boolean;
scrollSpyDelay?: number;
scrollSpyOnce?: boolean;
onCompleteCallback?: () => any;
plugin?: CountUpPlugin;
}
export declare interface CountUpPlugin {
render(elem: HTMLElement, formatted: string): void;
}
export declare class CountUp {
private endVal;
options?: CountUpOptions;
version: string;
private defaults;
private rAF;
private startTime;
private remaining;
private finalEndVal;
private useEasing;
private countDown;
el: HTMLElement | HTMLInputElement;
formattingFn: (num: number) => string;
easingFn?: (t: number, b: number, c: number, d: number) => number;
error: string;
startVal: number;
duration: number;
paused: boolean;
frameVal: number;
once: boolean;
constructor(target: string | HTMLElement | HTMLInputElement, endVal: number, options?: CountUpOptions);
handleScroll(self: CountUp): void;
/**
* Smart easing works by breaking the animation into 2 parts, the second part being the
* smartEasingAmount and first part being the total amount minus the smartEasingAmount. It works
* by disabling easing for the first part and enabling it on the second part. It is used if
* usingEasing is true and the total animation amount exceeds the smartEasingThreshold.
*/
private determineDirectionAndSmartEasing;
start(callback?: (args?: any) => any): void;
pauseResume(): void;
reset(): void;
update(newEndVal: string | number): void;
count: (timestamp: number) => void;
printValue(val: number): void;
ensureNumber(n: any): boolean;
validateValue(value: string | number): number;
private resetDuration;
formatNumber: (num: number) => string;
easeOutExpo: (t: number, b: number, c: number, d: number) => number;
}
這里 export 了一個(gè) CountUp 類 還有一個(gè) CountUpOptions 的interface, CountUp 類的 constructor 接收三個(gè)參數(shù), 分別是 dom節(jié)點(diǎn), endVal, 以及 options, 我們將這三個(gè)參數(shù)當(dāng)成是 props 傳入同時(shí)給定默認(rèn)值, , 首先獲取span的ref作為 countUp初始化的容器 , 定義一個(gè)變量 numAnim 接收 new CountUp(countupRef.value, props.end, props.options) 的返回值, , 在 onMounted中初始化countUp.js,接著我們就可以去頁面引入 CountUp.vue 看看效果,因?yàn)橛心J(rèn)值,所以我們不需要傳入任何參數(shù), 直接看就好了, 此時(shí)CountUp.vue組件代碼如下,
<script setup lang="ts">
import { CountUp } from 'countup.js'
import type { CountUpOptions } from 'countup.js'
import { onMounted, ref } from 'vue'
let numAnim = ref(null) as any
const countupRef = ref()
const props = defineProps({
end: {
type: Number,
default: 2023
},
options: {
type: Object,
default() {
let options: CountUpOptions = {
startVal: 0, // 開始的數(shù)字 一般設(shè)置0開始
decimalPlaces: 2, // number類型 小數(shù)位,整數(shù)自動(dòng)添.00
duration: 2, // number類型 動(dòng)畫延遲秒數(shù),默認(rèn)值是2
useGrouping: true, // boolean類型 是否開啟逗號(hào),默認(rèn)true(1,000)false(1000)
useEasing: true, // booleanl類型 動(dòng)畫緩動(dòng)效果(ease),默認(rèn)true
smartEasingThreshold: 500, // numberl類型 大于這個(gè)數(shù)值的值開啟平滑緩動(dòng)
smartEasingAmount: 300, // numberl類型
separator: ',',// string 類型 分割用的符號(hào)
decimal: '.', // string 類型 小數(shù)分割符合
prefix: '¥', // sttring 類型 數(shù)字開頭添加固定字符
suffix: '元', // sttring類型 數(shù)字末尾添加固定字符
numerals: [] // Array類型 替換從0到9對(duì)應(yīng)的字,也就是自定數(shù)字字符了,數(shù)組存儲(chǔ)
}
return options
}
}
})
onMounted(() => {
initCount()
})
const initCount = () => {
numAnim = new CountUp(countupRef.value, props.end, props.options)
numAnim.start()
}
</script>
<template>
<span ref="countupRef"></span>
</template>
這時(shí)我們發(fā)現(xiàn),在 onMounted 執(zhí)行之后, 如果我們的endVal值發(fā)生了改動(dòng), 由于 CountUp.vue的 onMounted 已經(jīng)完成,并不會(huì)同步修改, 如果我們的值是異步獲取的,會(huì)造成渲染不出我們想要的結(jié)果,那么我們就需要在組件中把這個(gè) initCount 方法給暴露給父組件使用,在vue3中,我們只需要使用 defineExpose 暴露即可, 同時(shí)我們也進(jìn)一步完善一下我們的props, 校驗(yàn)限制一下傳入的optinos值, 盡量避免使用上的錯(cuò)誤, 同時(shí)修改一下默認(rèn)值,避免造成一些問題,最終的代碼如下
<script setup lang="ts">
import { CountUp } from 'countup.js'
import type { CountUpOptions } from 'countup.js'
import { onMounted, ref } from 'vue'
let numAnim = ref(null) as any
const countupRef = ref()
const props = defineProps({
end: {
type: Number,
default: 0
},
options: {
type: Object,
validator(option: Object) {
let keys = ['startVal', 'decimalPlaces', 'duration', 'useGrouping', 'useEasing', 'smartEasingThreshold', 'smartEasingAmount', 'separator', 'decimal', 'prefix', 'suffix', 'numerals']
for (const key in option) {
if (!keys.includes(key)) {
console.error(" CountUp 傳入的 options 值不符合 CountUpOptions")
return false
}
}
return true
},
default() {
let options: CountUpOptions = {
startVal: 0, // 開始的數(shù)字 一般設(shè)置0開始
decimalPlaces: 2, // number類型 小數(shù)位,整數(shù)自動(dòng)添.00
duration: 2, // number類型 動(dòng)畫延遲秒數(shù),默認(rèn)值是2
useGrouping: true, // boolean類型 是否開啟逗號(hào),默認(rèn)true(1,000)false(1000)
useEasing: true, // booleanl類型 動(dòng)畫緩動(dòng)效果(ease),默認(rèn)true
smartEasingThreshold: 500, // numberl類型 大于這個(gè)數(shù)值的值開啟平滑緩動(dòng)
smartEasingAmount: 300, // numberl類型
separator: ',',// string 類型 分割用的符號(hào)
decimal: '.', // string 類型 小數(shù)分割符合
prefix: '', // sttring 類型 數(shù)字開頭添加固定字符
suffix: '', // sttring類型 數(shù)字末尾添加固定字符
numerals: [] // Array類型 替換從0到9對(duì)應(yīng)的字,也就是自定數(shù)字字符了,數(shù)組存儲(chǔ)
}
return options
}
}
})
onMounted(() => {
initCount()
})
const initCount = () => {
numAnim = new CountUp(countupRef.value, props.end, props.options)
numAnim.start()
}
defineExpose({
initCount
})
</script>
<template>
<span ref="countupRef"></span>
</template>
<style scoped lang='scss'></style>
文末
至此,CountUp 的組件開發(fā)已經(jīng)完成了,后續(xù)我們也可以根據(jù)自己的項(xiàng)目需求自行去調(diào)整組件。 這里是拿了一個(gè)很簡單的 countUp 組件舉了一個(gè)簡單例子,有的時(shí)候自己動(dòng)手豐衣足食,很多插件的封裝比想象中簡單的多。
到此這篇關(guān)于Vue3基于countUp.js實(shí)現(xiàn)數(shù)字滾動(dòng)的插件的文章就介紹到這了,更多相關(guān)Vue3 countUp.js數(shù)字滾動(dòng)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Javascript createElement和innerHTML增加頁面元素的性能對(duì)比
Javascript之createElement和innerHTML增加頁面元素的性能對(duì)比2009-09-09
JavaScript設(shè)計(jì)模式中的觀察者模式
這篇文章主要介紹了JavaScript設(shè)計(jì)模式中的觀察者模式,觀察者設(shè)計(jì)模式適用于監(jiān)聽一對(duì)多的操作,例如監(jiān)聽對(duì)象屬性的修改等等,觀察者模式能夠降低代碼耦合度,提升可擴(kuò)展性2022-06-06
javascript框架設(shè)計(jì)之框架分類及主要功能
這篇文章主要介紹了javascript框架設(shè)計(jì)之框架分類及主要功能的相關(guān)資料,需要的朋友可以參考下2015-06-06
詳解JavaScript數(shù)組過濾相同元素的5種方法
本篇文章主要介紹了詳解JavaScript數(shù)組過濾相同元素的5種方法,詳細(xì)的介紹了5種實(shí)用方法,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2017-05-05
IE 下Enter提交表單存在重復(fù)提交問題的解決方法
這篇文章主要介紹了IE 下Enter提交表單存在重復(fù)提交問題的解決方法,需要的朋友可以參考下2014-05-05
如何用js 實(shí)現(xiàn)依賴注入的思想,后端框架思想搬到前端來
這篇文章主要介紹了js 實(shí)現(xiàn)依賴注入的思想,后端框架思想搬到前端來,需要的朋友可以參考下2015-08-08

