Vue3基於countUp.js怎麼實現數字滾動的插件
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中文網其他相關文章!

熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

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

熱門文章

熱工具

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

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

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

tinymce是一個功能齊全的富文本編輯器插件,但在vue中引入tinymce並不像別的Vue富文本插件一樣那麼順利,tinymce本身並不適配Vue,還需要引入@tinymce/tinymce-vue,並且它是國外的富文本插件,沒有透過中文版本,需要在其官網下載翻譯包(可能需要翻牆)。 1.安裝相關依賴npminstalltinymce-Snpminstall@tinymce/tinymce-vue-S2、下載中文包3.引入皮膚和漢化包在項目public資料夾下新建tinymce資料夾,將下載的

vue3+vite:src使用require動態導入圖片報錯和解決方法vue3+vite動態的導入多張圖片vue3如果使用的是typescript開發,就會出現require引入圖片報錯,requireisnotdefined不能像使用vue2這樣imgUrl:require(' …/assets/test.png')導入,是因為typescript不支援require所以用import導入,下面介紹如何解決:使用awaitimport

想要實現頁面的局部刷新,我們只需要實現局部元件(dom)的重新渲染。在Vue中,想要實現這效果最簡單的方式方法就是使用v-if指令。在Vue2中我們除了使用v-if指令讓局部dom的重新渲染,也可以新建一個空白元件,需要刷新局部頁面時跳轉至這個空白元件頁面,然後在空白元件內的beforeRouteEnter守衛中又跳轉回原來的頁面。如下圖所示,如何在Vue3.X中實現點擊刷新按鈕實現紅框範圍內的dom重新加載,並展示對應的加載狀態。由於Vue3.X中scriptsetup語法中組件內守衛只有o

Vue實作部落格前端,需要實作markdown的解析,如果有程式碼則需要實作程式碼的高亮。 Vue的markdown解析函式庫很多,如markdown-it、vue-markdown-loader、marked、vue-markdown等。這些庫都大同小異。這裡選用的是marked,程式碼高亮的函式庫選用的是highlight.js。具體實現步驟如下:一、安裝依賴庫在vue專案下開啟命令窗口,並輸入以下命令npminstallmarked-save//marked用於將markdown轉換成htmlnpmins

vue3+ts+axios+pinia實作無感刷新1.先在專案中下載aiXos和pinianpmipinia--savenpminstallaxios--save2.封裝axios請求-----下載js-cookienpmiJS-cookie-s//引入aixosimporttype{AxiosRequestConfigig ,AxiosResponse}from"axios";importaxiosfrom'axios';import{ElMess

前言無論是vue還是react,當我們遇到多處重複程式碼的時候,我們都會想著如何重複使用這些程式碼,而不是一個檔案裡充斥著一堆冗餘程式碼。實際上,vue和react都可以透過抽組件的方式來達到復用,但如果遇到一些很小的程式碼片段,你又不想抽到另外一個檔案的情況下,相比而言,react可以在相同文件裡面宣告對應的小元件,或透過renderfunction來實現,如:constDemo:FC=({msg})=>{returndemomsgis{msg}}constApp:FC=()=>{return(

最終效果安裝VueCropper組件yarnaddvue-cropper@next上面的安裝值針對Vue3的,如果時Vue2或想使用其他的方式引用,請訪問它的npm官方地址:官方教程。在元件中引用使用時也很簡單,只需要引入對應的元件和它的樣式文件,我這裡沒有在全域引用,只在我的元件檔案中引入import{userInfoByRequest}from'../js/api' import{VueCropper}from'vue-cropper&

vue3專案打包發佈到伺服器後存取頁面顯示空白1、處理vue.config.js檔案中的publicPath處理如下:const{defineConfig}=require('@vue/cli-service')module.exports=defineConfig({publicPath :process.env.NODE_ENV==='production'?'./':'/&
