ホームページ  >  記事  >  ウェブフロントエンド  >  countUp.js に基づいて Vue3 にデジタル スクロール プラグインを実装する方法

countUp.js に基づいて Vue3 にデジタル スクロール プラグインを実装する方法

WBOY
WBOY転載
2023-05-10 22:19:041919ブラウズ

countUp の概要

CountUp.js は、依存関係のない軽量の JavaScript クラスで、数値データをより興味深い方法で表示するアニメーションをすばやく作成するために使用できます。 CountUp は、渡された開始値と終了値に応じて、両方向にカウントできます。

市場には countUp.js の二次カプセル化に基づいた Vue コンポーネントが多数ありますが、サードパーティ コンポーネントの更新頻度を保証するのが難しいため、私は個人的にはこれらのサードパーティのカプセル化を使用したくありません。おそらく作者は、それを維持し続けるつもりはなく、気まぐれにカプセル化してアップロードしただけかもしれません。それが使用される場合、それは将来的にまったく維持できなくなることを意味するため、この二次カプセル化を次の方法で実装することをお勧めしますこのカプセル化を通じて、このことに慣れることができますvue3ts 構文

countUp コンポーネント パッケージ

最初のインストール

npm i countup.js

インストール後、新しいファイル CountUp.vue を作成します。テンプレート部分は非常にシンプルです。必要なのは 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;
}

ここで

CountUp# がエクスポートされました ## このクラスには CountUpOptions のインターフェイスもあります。 CountUp クラスは 3 つのパラメーター、つまり dom ノード、endVal、オプションを受け取ります。これら 3 つのパラメーターは props として渡され、デフォルト値が与えられます。まず、span の ref を取得します。 countUp 初期化のコンテナとして、##new CountUp(countupRef.value, props.end, props.options)## の戻り値を受け取る変数 numAnim を定義します#, , は onMountedcountUp.js で初期化されているので、このページでは CountUp.vue を紹介して効果を確認します。 , パラメータを渡す必要はありません。ただ見てください。この時点で、CountUp.vue コンポーネントのコードは次のとおりです。<pre class="brush:js;">&lt;script setup lang=&quot;ts&quot;&gt; import { CountUp } from &amp;#39;countup.js&amp;#39; import type { CountUpOptions } from &amp;#39;countup.js&amp;#39; import { onMounted, ref } from &amp;#39;vue&amp;#39; 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: &amp;#39;,&amp;#39;,// string 类型 分割用的符号 decimal: &amp;#39;.&amp;#39;, // string 类型 小数分割符合 prefix: &amp;#39;¥&amp;#39;, // sttring 类型 数字开头添加固定字符 suffix: &amp;#39;元&amp;#39;, // sttring类型 数字末尾添加固定字符 numerals: [] // Array类型 替换从0到9对应的字,也就是自定数字字符了,数组存储 } return options } } }) onMounted(() =&gt; { initCount() }) const initCount = () =&gt; { numAnim = new CountUp(countupRef.value, props.end, props.options) numAnim.start() } &lt;/script&gt; &lt;template&gt; &lt;span ref=&quot;countupRef&quot;&gt;&lt;/span&gt; &lt;/template&gt;</pre>この時点で、次のことがわかりました。 onMounted の実行後、CountUp.vue

onMounted

により endVal 値が変更された場合、それは完了しており、同期的に変更されません。非同期的に取得すると、必要な結果がレンダリングされないため、この initCount メソッドをコンポーネント内の親に公開する必要があります。コンポーネントの使用、vue3 では、defineExpose## を使用するだけで済みます。同時に、プロパティをさらに改善し、受信する optinos 値を検証して制限し、Use エラーを回避し、問題の発生を避けるためにデフォルト値を変更します。最終的なコードは次のとおりです

<script setup lang="ts">
  import { CountUp } from &#39;countup.js&#39;
  import type { CountUpOptions } from &#39;countup.js&#39;
  import { onMounted, ref } from &#39;vue&#39;

  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 = [&#39;startVal&#39;, &#39;decimalPlaces&#39;, &#39;duration&#39;, &#39;useGrouping&#39;, &#39;useEasing&#39;, &#39;smartEasingThreshold&#39;, &#39;smartEasingAmount&#39;, &#39;separator&#39;, &#39;decimal&#39;, &#39;prefix&#39;, &#39;suffix&#39;, &#39;numerals&#39;]
        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: &#39;,&#39;,// string 类型 分割用的符号
          decimal: &#39;.&#39;, // string 类型  小数分割符合
          prefix: &#39;&#39;, // sttring 类型  数字开头添加固定字符
          suffix: &#39;&#39;, // 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=&#39;scss&#39;></style>

以上がcountUp.js に基づいて Vue3 にデジタル スクロール プラグインを実装する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はyisu.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。