溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Vue3基于countUp.js如何實現(xiàn)數(shù)字滾動的插件

發(fā)布時間:2023-05-11 11:21:29 來源:億速云 閱讀:286 作者:zzz 欄目:編程語言

這篇“Vue3基于countUp.js如何實現(xiàn)數(shù)字滾動的插件”文章的知識點大部分人都不太理解,所以小編給大家總結(jié)了以下內(nèi)容,內(nèi)容詳細,步驟清晰,具有一定的借鑒價值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來看看這篇“Vue3基于countUp.js如何實現(xiàn)數(shù)字滾動的插件”文章吧。

countUp 簡介

CountUp.js 是一種無依賴項的輕量級 JavaScript 類,可用于快速創(chuàng)建以更有趣的方式顯示數(shù)字數(shù)據(jù)的動畫。CountUp 可以在兩個方向上進行計數(shù),具體取決于傳遞的開始和結(jié)束值。

雖然現(xiàn)在市面上基于 countUp.js 二次封裝的Vue組件不在少數(shù), 但我個人是不太喜歡使用這些第三方封裝的,因為第三方組件的更新頻率很難保證,也許作者只是一時興起封裝上傳了, 并未打算繼續(xù)維護,如果使用了 等于后續(xù)根本沒有維護性了, 所以這種二次封裝我推薦自行實現(xiàn), 我們可以通過本次封裝熟悉一下 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 接收三個參數(shù), 分別是 dom節(jié)點, endVal, 以及 options, 我們將這三個參數(shù)當(dāng)成是 props 傳入同時給定默認值, , 首先獲取span的ref作為 countUp初始化的容器 , 定義一個變量 numAnim 接收 new CountUp(countupRef.value, props.end, props.options) 的返回值, , 在 onMounted中初始化countUp.js,接著我們就可以去頁面引入 CountUp.vue 看看效果,因為有默認值,所以我們不需要傳入任何參數(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ù)自動添.00
          duration: 2, // number類型 動畫延遲秒數(shù),默認值是2
          useGrouping: true, // boolean類型  是否開啟逗號,默認true(1,000)false(1000)
          useEasing: true,  // booleanl類型 動畫緩動效果(ease),默認true
          smartEasingThreshold: 500, // numberl類型 大于這個數(shù)值的值開啟平滑緩動
          smartEasingAmount: 300, // numberl類型
          separator: ',',// string 類型 分割用的符號
          decimal: '.', // string 類型  小數(shù)分割符合
          prefix: '¥', // sttring 類型  數(shù)字開頭添加固定字符
          suffix: '元', // sttring類型 數(shù)字末尾添加固定字符
          numerals: []  // Array類型 替換從0到9對應(yīng)的字,也就是自定數(shù)字字符了,數(shù)組存儲
        }
        return options
      }
    }
  })
  onMounted(() => {
    initCount()
  })
  const initCount = () => {
    numAnim = new CountUp(countupRef.value, props.end, props.options)
    numAnim.start()
  }
</script>

<template>
  <span ref="countupRef"></span>
</template>

這時我們發(fā)現(xiàn),在 onMounted 執(zhí)行之后, 如果我們的endVal值發(fā)生了改動, 由于 CountUp.vueonMounted 已經(jīng)完成,并不會同步修改, 如果我們的值是異步獲取的,會造成渲染不出我們想要的結(jié)果,那么我們就需要在組件中把這個 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, // 開始的數(shù)字  一般設(shè)置0開始
          decimalPlaces: 2, // number類型 小數(shù)位,整數(shù)自動添.00
          duration: 2, // number類型 動畫延遲秒數(shù),默認值是2
          useGrouping: true, // boolean類型  是否開啟逗號,默認true(1,000)false(1000)
          useEasing: true,  // booleanl類型 動畫緩動效果(ease),默認true
          smartEasingThreshold: 500, // numberl類型 大于這個數(shù)值的值開啟平滑緩動
          smartEasingAmount: 300, // numberl類型
          separator: ',',// string 類型 分割用的符號
          decimal: '.', // string 類型  小數(shù)分割符合
          prefix: '', // sttring 類型  數(shù)字開頭添加固定字符
          suffix: '', // sttring類型 數(shù)字末尾添加固定字符
          numerals: []  // Array類型 替換從0到9對應(yīng)的字,也就是自定數(shù)字字符了,數(shù)組存儲
        }
        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>

以上就是關(guān)于“Vue3基于countUp.js如何實現(xiàn)數(shù)字滾動的插件”這篇文章的內(nèi)容,相信大家都有了一定的了解,希望小編分享的內(nèi)容對大家有幫助,若想了解更多相關(guān)的知識內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI