찾다
웹 프론트엔드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으로 문의하세요.
@keyframes 및 @Media와 같이 @Rules는 얼마나 많은 특이성을 가지고 있습니까?@keyframes 및 @Media와 같이 @Rules는 얼마나 많은 특이성을 가지고 있습니까?Apr 18, 2025 am 11:34 AM

나는 다른 날이 질문을 받았다. 나의 첫 번째 생각은 : 이상한 질문입니다! 특이성은 선택기에 관한 것이며 At-Rules는 선택기가 아니므로 ... 무의미합니까?

@Media 및 @Support 쿼리를 중첩 할 수 있습니까?@Media 및 @Support 쿼리를 중첩 할 수 있습니까?Apr 18, 2025 am 11:32 AM

그렇습니다. 당신은 할 수 있습니다. 그리고 그것은 실제로 어떤 순서로 중요하지 않습니다. CSS 전 처리기가 필요하지 않습니다. 일반 CSS에서 작동합니다.

빠른 Gulp 캐시 파열빠른 Gulp 캐시 파열Apr 18, 2025 am 11:23 AM

CSS 및 JavaScript (및 이미지 및 글꼴 등)와 같은 자산에 멀리 떨어진 캐시 헤더를 설정해야합니다. 브라우저를 알려줍니다

CSS의 품질과 복잡성을 모니터링하는 스택을 찾아CSS의 품질과 복잡성을 모니터링하는 스택을 찾아Apr 18, 2025 am 11:22 AM

많은 개발자들은 CSS 코드베이스를 유지하는 방법에 대해 글을 썼지 만 코드베이스의 품질을 어떻게 측정하는지에 대해 많은 글을 쓰지 않습니다. 물론, 우리는 가지고 있습니다

Datalist는 가치를 시행하지 않고 값을 제안하는 것입니다Datalist는 가치를 시행하지 않고 값을 제안하는 것입니다Apr 18, 2025 am 11:08 AM

짧고 임의의 텍스트를 수락 해야하는 양식이 있습니까? 이름이나 다른 것 같습니다. 정확히 무엇을위한 것입니다. 많은 것이 있습니다

취리히에서 열린 전면 회의취리히에서 열린 전면 회의Apr 18, 2025 am 11:03 AM

나는 프론트 컨퍼런스를 위해 스위스 취리히로 향하게되어 매우 기쁩니다 (그 이름과 URL을 사랑합니다!). 나는 전에 스위스에 가본 적이 없기 때문에 나는 흥분했다

CloudFlare Workers와 함께 풀 스택 서버리스 애플리케이션 구축CloudFlare Workers와 함께 풀 스택 서버리스 애플리케이션 구축Apr 18, 2025 am 10:58 AM

소프트웨어 개발에서 제가 가장 좋아하는 개발 중 하나는 서버리스의 출현이었습니다. 세부 사항에 푹 빠지는 경향이있는 개발자로서

NUXT 응용 프로그램에서 동적 경로 생성NUXT 응용 프로그램에서 동적 경로 생성Apr 18, 2025 am 10:53 AM

이 게시물에서는 들어오는 데이터를 위해 동적 경로를 만드는 방법을 보여주기 위해 NetLify에 구축하고 배포 한 전자 상거래 상점 데모를 사용합니다. 상당히입니다

See all articles

핫 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 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

PhpStorm 맥 버전

PhpStorm 맥 버전

최신(2018.2.1) 전문 PHP 통합 개발 도구

SublimeText3 Linux 새 버전

SublimeText3 Linux 새 버전

SublimeText3 Linux 최신 버전

VSCode Windows 64비트 다운로드

VSCode Windows 64비트 다운로드

Microsoft에서 출시한 강력한 무료 IDE 편집기

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기