搜尋
首頁web前端css教學從香草JavaScript移動到可重複使用的Vue組件

從香草JavaScript移動到可重複使用的Vue組件

本文展示了將香草JavaScript倒數計時器重構為可重複使用的VUE組件。原始計時器在上一篇文章中詳細介紹,缺乏可重複性和有效的UI同步。這種轉換解決了這些缺點。

為什麼要使用vue?主要是有兩個原因:

  • 同步UI和計時器狀態:原始javaScript代碼在timerInterval函數中託管狀態,直接操縱DOM元素。 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.

以上是從香草JavaScript移動到可重複使用的Vue組件的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
模擬鼠標運動模擬鼠標運動Apr 22, 2025 am 11:45 AM

如果您曾經在現場演講或課程中必須顯示一個互動動畫,那麼您可能知道它並不總是那麼容易與您的幻燈片進行互動

通過Astro Action和Fuse.js為搜索提供動力通過Astro Action和Fuse.js為搜索提供動力Apr 22, 2025 am 11:41 AM

對於Astro,我們可以在構建過程中生成大部分網站,但是有一小部分服務器端代碼可以使用Fuse.js之類的搜索功能來處理搜索功能。在此演示中,我們將使用保險絲搜索一組個人“書籤”

未定義:第三個布爾值未定義:第三個布爾值Apr 22, 2025 am 11:38 AM

我想在我的一個項目中實現一條通知消息,類似於您在保存文檔時在Google文檔中看到的信息。換句話說,一個

捍衛三元聲明捍衛三元聲明Apr 22, 2025 am 11:25 AM

幾個月前,我正在使用黑客新聞(就像一個人一樣),並且遇到了一篇(現已刪除的)文章,內容涉及不使用if語句。如果您是這個想法的新手(就像我

使用網絡語音API進行多語言翻譯使用網絡語音API進行多語言翻譯Apr 22, 2025 am 11:23 AM

自科幻小說以來,我們就幻想著與我們交談的機器。今天這很普遍。即便如此,製造的技術

JetPack Gutenberg塊JetPack Gutenberg塊Apr 22, 2025 am 11:20 AM

我記得當古騰堡被釋放到核心時,因為那天我在WordCamp我們。現在已經過去了幾個月,所以我想我們越來越多的人

在VUE中創建可重複使用的分頁組件在VUE中創建可重複使用的分頁組件Apr 22, 2025 am 11:17 AM

大多數Web應用程序背後的想法是從數據庫中獲取數據,並以最佳方式將其呈現給用戶。當我們處理數據時

使用'盒子陰影”和剪輯路徑一起使用'盒子陰影”和剪輯路徑一起Apr 22, 2025 am 11:13 AM

讓我們在一個情況下做一些似乎有意義的事情的情況下逐步進行一些逐步,但是您仍然可以用CSS欺騙來完成它。在這個

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

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

熱工具

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版