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
):
- Import:
import BaseTimer from "./components/BaseTimer";
- Register:
components: { BaseTimer }
- 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 サイトの他の関連記事を参照してください。

ホットAIツール

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

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

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

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

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

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

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

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

ホットトピック











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

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

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

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

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

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

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