Lit

Joey·2024년 12월 2일
0

LitElement?

LitElement는 웹 컴포넌트를 쉽게 만들 수 있도록 도와주는 라이브러리입니다. JavaScript로 작성된 HTML 템플릿을 효율적으로 관리하고, 상태 변화에 따라 자동으로 UI를 업데이트하는 강력한 기능을 제공합니다.


1.소개

LitElement는 Google에서 개발한 웹 컴포넌트 라이브러리입니다. JavaScript로 구성된 웹 컴포넌트를 작성할 수 있도록 도와줍니다. LitElement의 주요 특징은 다음과 같습니다.

  • 반응형 속성: 속성 값의 변화에 따라 자동으로 UI를 업데이트합니다.
  • 템플릿: HTML과 JavaScript를 결합하여 동적으로 UI를 렌더링할 수 있습니다.
  • 간결한 문법: 웹 컴포넌트를 작성하는 데 필요한 최소한의 코드로 복잡한 UI를 관리할 수 있습니다.
  • 자동 최적화: 렌더링 최적화가 내장되어 있어 불필요한 DOM 업데이트를 최소화합니다.

2.설치

LitElement를 사용하기 위해서는 HTML 파일에서 CDN을 통해 로드할 수 있습니다. 또한, npm을 통해 설치할 수도 있습니다.

2.1 CDN을 통한 설치

<script type="module">
  import { LitElement, html, css } from 'https://cdn.jsdelivr.net/gh/lit/dist@3/core/lit-core.min.js';
</script>

2.2 NPM을 통한 설치

npm install lit 설치 후, import { LitElement, html, css } from 'lit';로 사용할 수 있습니다.

3.기본 구조

import { LitElement, html, css } from 'https://cdn.jsdelivr.net/gh/lit/dist@3/core/lit-core.min.js';

class MyComponent extends LitElement {
  // 속성 정의
  static properties = {
    name: { type: String }
  };

  constructor() {
    super();
    this.name = 'World';
  }

  // 템플릿 정의
  render() {
    return html`<p>Hello, ${this.name}!</p>`;
  }
}

customElements.define('my-component', MyComponent);

3.1 LitElement 클래스

LitElement는 모든 Lit 컴포넌트의 기본 클래스입니다.
컴포넌트는 LitElement를 상속하여 정의됩니다.

3.2 static properties

properties는 컴포넌트에서 사용될 속성들을 정의합니다.
속성 값의 변경을 추적하여 UI를 자동으로 업데이트합니다.

3.3 constructor

constructor는 컴포넌트가 생성될 때 초기값을 설정합니다.

3.4 render

render 메서드는 HTML 템플릿을 반환합니다.
html 템플릿 리터럴을 사용하여 동적인 UI를 렌더링합니다.

3.5 customElements.define

컴포넌트를 브라우저에 등록하기 위해 customElements.define 메서드를 사용합니다.
첫 번째 인자는 컴포넌트의 이름, 두 번째 인자는 컴포넌트 클래스입니다.


4.스타일 관리

LitElement는 컴포넌트 내에서 스타일을 관리하는 방법도 제공합니다. 스타일을 static styles로 정의할 수 있습니다.

4.1 스타일 정의

static styles = css`
  :host {
    display: block;
    padding: 16px;
    background-color: #f3f3f3;
  }

  p {
    color: blue;
  }
`;

4.2 css 템플릿 리터럴

css 템플릿 리터럴을 사용하여 컴포넌트 내 스타일을 정의합니다.
:host 선택자는 컴포넌트의 최상위 요소를 스타일링합니다.


5.속성 관리

LitElement는 속성 값의 변화를 감지하고 UI를 자동으로 업데이트합니다. 속성에 type을 지정할 수 있으며, 이를 통해 속성의 데이터 타입을 정의합니다.

5.1 속성 데이터 타입

static properties = {
  name: { type: String },
  age: { type: Number },
};

5.2 속성 업데이트

this.name = 'John';
속성 값이 변경되면 render 메서드가 자동으로 호출되어 UI가 업데이트됩니다.


6.이벤트 리스너 추가

render() {
  return html`
    <button @click=${this.handleClick}>Click me</button>
  `;
}

handleClick() {
  this.name = 'Clicked!';
}

LitElement@event 데코레이터를 사용하여 이벤트 리스너를 쉽게 추가할 수 있습니다.

@click=${this.handleClick}는 버튼 클릭 시 handleClick 메서드를 호출합니다.

이벤트 리스너는 DOM에 추가된 후에 동작합니다.


7.템플릿과 조건부 렌더링

render() {
  return html`
    ${this.name === 'World' ? html`<p>Hello, World!</p>` : html`<p>Goodbye, World!</p>`}
  `;
}

name 속성의 값에 따라 다른 템플릿을 렌더링합니다.


8.다른 파일에서 사용하기

export

// component.js
import { LitElement, html } from 'https://cdn.jsdelivr.net/gh/lit/dist@3/core/lit-core.min.js';

class MyComponent extends LitElement {
  static properties = { name: { type: String } };

  constructor() {
    super();
    this.name = 'World';
  }

  render() {
    return html`<p>Hello, ${this.name}!</p>`;
  }
}

customElements.define('my-component', MyComponent);

export default MyComponent;

import

// main.js
import MyComponent from './component.js';

HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>My Page</title>
    <script src="main.js" type="module"></script>
  </head>
  <body>
    <my-component></my-component>
  </body>
</html>
profile
멋쟁이사자처럼 프론트엔드 부트캠프 12기

0개의 댓글