이 기사는 바닐라 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
):
- 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.
위 내용은 바닐라 JavaScript에서 재사용 가능한 VUE 구성 요소로 이동합니다의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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

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

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

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

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

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

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

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


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

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

인기 기사

뜨거운 도구

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

SublimeText3 Linux 새 버전
SublimeText3 Linux 최신 버전

VSCode Windows 64비트 다운로드
Microsoft에서 출시한 강력한 무료 IDE 편집기

ZendStudio 13.5.1 맥
강력한 PHP 통합 개발 환경

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기
