목차
템플릿 및 스타일
상수 및 변수
Reactive Variables
Computed Properties
Using Data and Computed Properties in the Template
Methods and Lifecycle Hooks
Component Usage
웹 프론트엔드 CSS 튜토리얼 바닐라 JavaScript에서 재사용 가능한 VUE 구성 요소로 이동합니다

바닐라 JavaScript에서 재사용 가능한 VUE 구성 요소로 이동합니다

Apr 11, 2025 am 09:40 AM

바닐라 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으로 문의하세요.

핫 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 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

<gum> : Bubble Gum Simulator Infinity- 로얄 키를 얻고 사용하는 방법
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
Nordhold : Fusion System, 설명
1 몇 달 전 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora : 마녀 트리의 속삭임 - Grappling Hook 잠금 해제 방법
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

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

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

정적 양식 공급자의 비교 정적 양식 공급자의 비교 Apr 16, 2025 am 11:20 AM

"정적 양식 공급자"라는 용어를 동전하려고합시다. 당신은 당신의 HTML을 가져옵니다

주간 플랫폼 뉴스 : HTML로드 속성, 주요 ARIA 사양 및 iframe에서 Shadow Dom으로 이동 주간 플랫폼 뉴스 : HTML로드 속성, 주요 ARIA 사양 및 iframe에서 Shadow Dom으로 이동 Apr 17, 2025 am 10:55 AM

이번 주에 플랫폼 뉴스 라운드 업 RONDUP, Chrome은로드에 대한 새로운 속성, 웹 개발자를위한 접근성 사양 및 BBC Move를 소개합니다.

Sass를 더 빨리 만들기위한 개념 증명 Sass를 더 빨리 만들기위한 개념 증명 Apr 16, 2025 am 10:38 AM

새로운 프로젝트가 시작될 때, Sass 컴파일은 눈을 깜박이게합니다. 특히 BrowserSync와 짝을 이루는 경우 기분이 좋습니다.

HTML 대화 요소와 함께 일부 실습 HTML 대화 요소와 함께 일부 실습 Apr 16, 2025 am 11:33 AM

이것은 처음으로 HTML 요소를보고 있습니다. 나는 그것을 잠시 동안 알고 있었지만 아직 스핀을 위해 그것을 가져 갔다. 그것은 꽤 시원하고 있습니다

PaperForm PaperForm Apr 16, 2025 am 11:24 AM

구매 또는 빌드는 기술 분야의 고전적인 논쟁입니다. 신용 카드 청구서에 라인 항목이 없기 때문에 물건을 구축하는 것이 저렴할 수 있지만

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

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

'Podcast 구독'링크는 어디에서 링크해야합니까? 'Podcast 구독'링크는 어디에서 링크해야합니까? Apr 16, 2025 pm 12:04 PM

한동안 iTunes는 팟 캐스팅에서 큰 개 였으므로 "Podcast 구독"을 링크 한 경우 다음과 같습니다.

주간 플랫폼 뉴스 : 텍스트 간격 북마크, 최상위 차단, 새로운 앰프 로딩 표시기 주간 플랫폼 뉴스 : 텍스트 간격 북마크, 최상위 차단, 새로운 앰프 로딩 표시기 Apr 17, 2025 am 11:26 AM

이번 주에 타이포그래피를 검사하기위한 편리한 북마크 인 Roundup, JavaScript 모듈과 Facebook의 Facebook 등을 어떻게 가져 오는지 땜질하기 위해 대기하는 편리한 북마크 인 Roundup과 Facebook의

See all articles