目次
テンプレートとスタイル
定数と変数
Reactive Variables
Computed Properties
Using Data and Computed Properties in the Template
Methods and Lifecycle Hooks
Component Usage
ホームページ ウェブフロントエンド CSSチュートリアル Vanilla JavaScriptから再利用可能なVueコンポーネントに移動します

Vanilla JavaScriptから再利用可能なVueコンポーネントに移動します

Apr 11, 2025 am 09:40 AM

Vanilla JavaScriptから再利用可能なVueコンポーネントに移動します

この記事では、バニラJavaScriptカウントダウンタイマーを再利用可能なVUEコンポーネントにリファクタリングすることを示しています。以前の記事で詳述されている元のタイマーは、再利用性と効率的なUI同期を欠いていました。この変換は、これらの欠点に対処します。

なぜVueを使用するのですか?主に2つの理由で:

  • 同期されたUIとタイマー状態: timerInterval関数内で、DOM要素を直接操作する元のJavaScriptコードが状態を管理しました。 Vueのテンプレート構文は、DOMをコンポーネントのデータに宣言して結合し、UIの更新を簡素化します。
  • 再利用性:元のタイマーは要素IDに依存しており、再利用性を制限しています。 VUEコンポーネントはロジックをカプセル化し、単一ページで複数の独立したタイマーインスタンスを有効にします。

これがVUEの実装です:

テンプレートとスタイル

VueはHTMLベースのテンプレートシステムを使用します。次の構造を持つBaseTimer.vueファイルを作成します。

<code><template>
  
</template>

<script>
  // ...
</script>

<style scoped>
  /* ... */
</style></code>
ログイン後にコピー

<template></template>セクションには、タイマーのマークアップ(主に前の記事のSVG)が含まれています。

<template>
  <div class="base-timer">
    <svg viewbox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
      <g>
        <circle cx="50" cy="50" r="45"></circle>
        <path :class="remainingPathColor" :stroke-dasharray="circleDasharray" d="
            M 50, 50
            m -45, 0
            a 45,45 0 1,0 90,0
            a 45,45 0 1,0 -90,0
          "></path>
      </g>
    </svg>
    {{ formattedTimeLeft }}
  </div>
</template>

<style scoped>
.base-timer {
  position: relative;
  width: 100px;
  height: 100px;
}
</style>タイマーの主要な側面は、 <code>stroke-dasharray</code> 、 <code>remainingPathColor</code> 、 <code>formatTime(timeLeft)</code>データバインディングを通じて制御されます。<h3 id="定数と変数">定数と変数</h3><p><script> section defines constants and variables.  Constants, such as <code>FULL_DASH_ARRAY, <code>WARNING_THRESHOLD, <code>ALERT_THRESHOLD, and <code>COLOR_CODES, are defined directly.</script></p>
<p>Variables are categorized: those directly re-assigned in methods (<code>timerInterval</code>, <code>timePassed</code>) and those dependent on other variables (<code>timeLeft</code>, <code>remainingPathColor</code>).</p>
<h4 id="Reactive-Variables">Reactive Variables</h4>
<p>Variables directly modified in methods are declared within the <code>data()</code> method to leverage Vue's reactivity system:</p>
<pre class="brush:php;toolbar:false">data() {
  return {
    timePassed: 0,
    timerInterval: null
  };
},
ログイン後にコピー

Computed Properties

Variables dependent on other variables are implemented as computed properties:

computed: {
  timeLeft() {
    return TIME_LIMIT - this.timePassed;
  },
  circleDasharray() {
    return `${(this.timeFraction * FULL_DASH_ARRAY).toFixed(0)} 283`;
  },
  formattedTimeLeft() {
    // ... (time formatting logic) ...
  },
  timeFraction() {
    // ... (time fraction calculation) ...
  },
  remainingPathColor() {
    // ... (color calculation based on timeLeft) ...
  }
},
ログイン後にコピー

Computed properties are pure functions, cached for efficiency.

Using Data and Computed Properties in the Template

The template utilizes text interpolation ({{ ... }}) and v-bind (or its shorthand :) directives to dynamically bind data and computed properties to the DOM.

Methods and Lifecycle Hooks

The startTimer method, simplified due to the use of computed properties, is called within the mounted() lifecycle hook:

methods: {
  startTimer() {
    this.timerInterval = setInterval(() => (this.timePassed  = 1), 1000);
  }
},
mounted() {
  this.startTimer();
},
ログイン後にコピー

Component Usage

To use the BaseTimer component in another component (e.g., App.vue):

  1. Import: import BaseTimer from "./components/BaseTimer";
  2. Register: components: { BaseTimer }
  3. Instantiate: <basetimer></basetimer> in the template.

This refactoring demonstrates the benefits of using Vue components for improved code organization, reusability, and efficient state management. The resulting component is self-contained and easily integrated into larger applications.

以上がVanilla JavaScriptから再利用可能なVueコンポーネントに移動しますの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

Vue 3 Vue 3 Apr 02, 2025 pm 06:32 PM

それは&#039; Vueチームにそれを成し遂げてくれておめでとうございます。それは大規模な努力であり、長い時間がかかったことを知っています。すべての新しいドキュメントも同様です。

ブラウザから有効なCSSプロパティ値を取得できますか? ブラウザから有効なCSSプロパティ値を取得できますか? Apr 02, 2025 pm 06:17 PM

私はこの非常に正当な質問で誰かに書いてもらいました。 Leaは、ブラウザから有効なCSSプロパティ自体を取得する方法についてブログを書いています。それはこのようなものです。

CI/CDで少し CI/CDで少し Apr 02, 2025 pm 06:21 PM

「ウェブサイト」は「モバイルアプリ」よりも適していると言いますが、Max Lynchからのこのフレーミングが好きです。

粘着性のあるポジショニングとサスのダッシュを備えた積み重ねられたカード 粘着性のあるポジショニングとサスのダッシュを備えた積み重ねられたカード Apr 03, 2025 am 10:30 AM

先日、Corey Ginnivanのウェブサイトから、この特に素敵なビットを見つけました。そこでは、スクロール中にカードのコレクションが互いに積み重ねられていました。

WordPressブロックエディターでのマークダウンとローカリゼーションを使用します WordPressブロックエディターでのマークダウンとローカリゼーションを使用します Apr 02, 2025 am 04:27 AM

WordPressエディターでユーザーに直接ドキュメントを表示する必要がある場合、それを行うための最良の方法は何ですか?

レスポンシブデザインのブラウザを比較します レスポンシブデザインのブラウザを比較します Apr 02, 2025 pm 06:25 PM

これらのデスクトップアプリがいくつかあり、目標があなたのサイトをさまざまな次元ですべて同時に表示しています。たとえば、書くことができます

フレックスレイアウト内の紫色のスラッシュ領域が誤って「オーバーフロー空間」と見なされるのはなぜですか? フレックスレイアウト内の紫色のスラッシュ領域が誤って「オーバーフロー空間」と見なされるのはなぜですか? Apr 05, 2025 pm 05:51 PM

フレックスレイアウトの紫色のスラッシュ領域に関する質問フレックスレイアウトを使用すると、開発者ツールなどの混乱する現象に遭遇する可能性があります(D ...

スティッキーヘッダーとフッターにCSSグリッドを使用する方法 スティッキーヘッダーとフッターにCSSグリッドを使用する方法 Apr 02, 2025 pm 06:29 PM

CSS Gridは、レイアウトをこれまで以上に簡単にするように設計されたプロパティのコレクションです。何でもするように、少し学習曲線がありますが、グリッドは

See all articles