countUp 簡介
CountUp.js 是一種無依賴項的輕量級 JavaScript 類,可用於快速建立以更有趣的方式顯示數位資料的動畫。 CountUp 可以在兩個方向上進行計數,具體取決於傳遞的開始和結束值。
雖然現在市面上基於countUp.js 二次封裝的Vue元件不在少數, 但我個人是不太喜歡使用這些第三方封裝的,因為第三方元件的更新頻率很難保證,也許作者只是一時興起封裝上傳了, 並未打算繼續維護,如果使用了等於後續根本沒有維護性了, 所以這種二次封裝我推薦自行實現, 我們可以透過本次封裝熟悉一下vue3
, ts
的語法
countUp 元件封裝
首先進行安裝
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怎麼實現數字滾動的插件的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Vue.js與前端技術棧緊密集成,提升開發效率和用戶體驗。 1)構建工具:與Webpack、Rollup集成,實現模塊化開發。 2)狀態管理:與Vuex集成,管理複雜應用狀態。 3)路由:與VueRouter集成,實現單頁面應用路由。 4)CSS預處理器:支持Sass、Less,提升樣式開發效率。

Netflix選擇React來構建其用戶界面,因為React的組件化設計和虛擬DOM機制能夠高效處理複雜界面和頻繁更新。 1)組件化設計讓Netflix將界面分解成可管理的小組件,提高了開發效率和代碼可維護性。 2)虛擬DOM機制通過最小化DOM操作,確保了Netflix用戶界面的流暢性和高性能。

Vue.js被開發者喜愛因為它易於上手且功能強大。 1)其響應式數據綁定係統自動更新視圖。 2)組件系統提高了代碼的可重用性和可維護性。 3)計算屬性和偵聽器增強了代碼的可讀性和性能。 4)使用VueDevtools和檢查控制台錯誤是常見的調試技巧。 5)性能優化包括使用key屬性、計算屬性和keep-alive組件。 6)最佳實踐包括清晰的組件命名、使用單文件組件和合理使用生命週期鉤子。

Vue.js是一個漸進式的JavaScript框架,適用於構建高效、可維護的前端應用。其關鍵特性包括:1.響應式數據綁定,2.組件化開發,3.虛擬DOM。通過這些特性,Vue.js簡化了開發過程,提高了應用性能和可維護性,使其在現代Web開發中備受歡迎。

Vue.js和React各有優劣,選擇取決於項目需求和團隊情況。 1)Vue.js適合小型項目和初學者,因其簡潔和易上手;2)React適用於大型項目和復雜UI,因其豐富的生態系統和組件化設計。

Vue.js通過多種功能提升用戶體驗:1.響應式系統實現數據即時反饋;2.組件化開發提高代碼復用性;3.VueRouter提供平滑導航;4.動態數據綁定和過渡動畫增強交互效果;5.錯誤處理機制確保用戶反饋;6.性能優化和最佳實踐提升應用性能。

Vue.js在Web開發中的角色是作為一個漸進式JavaScript框架,簡化開發過程並提高效率。 1)它通過響應式數據綁定和組件化開發,使開發者能專注於業務邏輯。 2)Vue.js的工作原理依賴於響應式系統和虛擬DOM,優化性能。 3)實際項目中,使用Vuex管理全局狀態和優化數據響應性是常見實踐。

Vue.js是由尤雨溪在2014年發布的漸進式JavaScript框架,用於構建用戶界面。它的核心優勢包括:1.響應式數據綁定,數據變化自動更新視圖;2.組件化開發,UI可拆分為獨立、可複用的組件。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

Dreamweaver Mac版
視覺化網頁開發工具

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。