這篇“Vue3基于countUp.js如何實現數字滾動的插件”文章的知識點大部分人都不太理解,所以小編給大家總結了以下內容,內容詳細,步驟清晰,具有一定的借鑒價值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來看看這篇“Vue3基于countUp.js如何實現數字滾動的插件”文章吧。
CountUp.js 是一種無依賴項的輕量級 JavaScript 類,可用于快速創建以更有趣的方式顯示數字數據的動畫。CountUp 可以在兩個方向上進行計數,具體取決于傳遞的開始和結束值。
雖然現在市面上基于 countUp.js 二次封裝的Vue組件不在少數, 但我個人是不太喜歡使用這些第三方封裝的,因為第三方組件的更新頻率很難保證,也許作者只是一時興起封裝上傳了, 并未打算繼續維護,如果使用了 等于后續根本沒有維護性了, 所以這種二次封裝我推薦自行實現, 我們可以通過本次封裝熟悉一下 vue3, ts 的語法
首先進行安裝
npm i countup.js
安裝好之后新建文件 CountUp.vue , template部分很簡單, 只需要一個span標簽, 同時給span一個 ref='countupRef' 就完成了,首先引入 countup.js, 按住Ctrl鼠標左鍵點擊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 了一個 CountUp 類 還有一個 CountUpOptions 的interface, CountUp 類的 constructor 接收三個參數, 分別是 dom節點, endVal, 以及 options, 我們將這三個參數當成是 props 傳入同時給定默認值, , 首先獲取span的ref作為 countUp初始化的容器 , 定義一個變量 numAnim 接收 new CountUp(countupRef.value, props.end, props.options) 的返回值, , 在 onMounted中初始化countUp.js,接著我們就可以去頁面引入 CountUp.vue 看看效果,因為有默認值,所以我們不需要傳入任何參數, 直接看就好了, 此時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, // 開始的數字 一般設置0開始
decimalPlaces: 2, // number類型 小數位,整數自動添.00
duration: 2, // number類型 動畫延遲秒數,默認值是2
useGrouping: true, // boolean類型 是否開啟逗號,默認true(1,000)false(1000)
useEasing: true, // booleanl類型 動畫緩動效果(ease),默認true
smartEasingThreshold: 500, // numberl類型 大于這個數值的值開啟平滑緩動
smartEasingAmount: 300, // numberl類型
separator: ',',// string 類型 分割用的符號
decimal: '.', // string 類型 小數分割符合
prefix: '¥', // sttring 類型 數字開頭添加固定字符
suffix: '元', // sttring類型 數字末尾添加固定字符
numerals: [] // Array類型 替換從0到9對應的字,也就是自定數字字符了,數組存儲
}
return options
}
}
})
onMounted(() => {
initCount()
})
const initCount = () => {
numAnim = new CountUp(countupRef.value, props.end, props.options)
numAnim.start()
}
</script>
<template>
<span ref="countupRef"></span>
</template>這時我們發現,在 onMounted 執行之后, 如果我們的endVal值發生了改動, 由于 CountUp.vue的 onMounted 已經完成,并不會同步修改, 如果我們的值是異步獲取的,會造成渲染不出我們想要的結果,那么我們就需要在組件中把這個 initCount 方法給暴露給父組件使用,在vue3中,我們只需要使用 defineExpose 暴露即可, 同時我們也進一步完善一下我們的props, 校驗限制一下傳入的optinos值, 盡量避免使用上的錯誤, 同時修改一下默認值,避免造成一些問題,最終的代碼如下
<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, // 開始的數字 一般設置0開始
decimalPlaces: 2, // number類型 小數位,整數自動添.00
duration: 2, // number類型 動畫延遲秒數,默認值是2
useGrouping: true, // boolean類型 是否開啟逗號,默認true(1,000)false(1000)
useEasing: true, // booleanl類型 動畫緩動效果(ease),默認true
smartEasingThreshold: 500, // numberl類型 大于這個數值的值開啟平滑緩動
smartEasingAmount: 300, // numberl類型
separator: ',',// string 類型 分割用的符號
decimal: '.', // string 類型 小數分割符合
prefix: '', // sttring 類型 數字開頭添加固定字符
suffix: '', // sttring類型 數字末尾添加固定字符
numerals: [] // Array類型 替換從0到9對應的字,也就是自定數字字符了,數組存儲
}
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>以上就是關于“Vue3基于countUp.js如何實現數字滾動的插件”這篇文章的內容,相信大家都有了一定的了解,希望小編分享的內容對大家有幫助,若想了解更多相關的知識內容,請關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。