LitElement는 웹 컴포넌트를 쉽게 만들 수 있도록 도와주는 라이브러리입니다. JavaScript로 작성된 HTML 템플릿을 효율적으로 관리하고, 상태 변화에 따라 자동으로 UI를 업데이트하는 강력한 기능을 제공합니다.
LitElement는 Google에서 개발한 웹 컴포넌트 라이브러리입니다. JavaScript로 구성된 웹 컴포넌트를 작성할 수 있도록 도와줍니다. LitElement의 주요 특징은 다음과 같습니다.
LitElement를 사용하기 위해서는 HTML 파일에서 CDN을 통해 로드할 수 있습니다. 또한, npm을 통해 설치할 수도 있습니다.
<script type="module">
import { LitElement, html, css } from 'https://cdn.jsdelivr.net/gh/lit/dist@3/core/lit-core.min.js';
</script>
npm install lit
설치 후, import { LitElement, html, css } from 'lit';로 사용할 수 있습니다.
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);
LitElement
는 모든 Lit 컴포넌트의 기본 클래스입니다.
컴포넌트는 LitElement
를 상속하여 정의됩니다.
properties
는 컴포넌트에서 사용될 속성들을 정의합니다.
속성 값의 변경을 추적하여 UI를 자동으로 업데이트합니다.
constructor
는 컴포넌트가 생성될 때 초기값을 설정합니다.
render
메서드는 HTML 템플릿을 반환합니다.
html 템플릿 리터럴을 사용하여 동적인 UI를 렌더링합니다.
컴포넌트를 브라우저에 등록하기 위해 customElements.define
메서드를 사용합니다.
첫 번째 인자는 컴포넌트의 이름, 두 번째 인자는 컴포넌트 클래스입니다.
LitElement
는 컴포넌트 내에서 스타일을 관리하는 방법도 제공합니다. 스타일을 static styles
로 정의할 수 있습니다.
static styles = css`
:host {
display: block;
padding: 16px;
background-color: #f3f3f3;
}
p {
color: blue;
}
`;
css 템플릿 리터럴을 사용하여 컴포넌트 내 스타일을 정의합니다.
:host
선택자는 컴포넌트의 최상위 요소를 스타일링합니다.
LitElement
는 속성 값의 변화를 감지하고 UI를 자동으로 업데이트합니다. 속성에 type
을 지정할 수 있으며, 이를 통해 속성의 데이터 타입을 정의합니다.
static properties = {
name: { type: String },
age: { type: Number },
};
this.name = 'John';
속성 값이 변경되면 render
메서드가 자동으로 호출되어 UI가 업데이트됩니다.
render() {
return html`
<button @click=${this.handleClick}>Click me</button>
`;
}
handleClick() {
this.name = 'Clicked!';
}
LitElement
는 @event
데코레이터를 사용하여 이벤트 리스너를 쉽게 추가할 수 있습니다.
@click=${this.handleClick}
는 버튼 클릭 시 handleClick
메서드를 호출합니다.
이벤트 리스너는 DOM
에 추가된 후에 동작합니다.
render() {
return html`
${this.name === 'World' ? html`<p>Hello, World!</p>` : html`<p>Goodbye, World!</p>`}
`;
}
name
속성의 값에 따라 다른 템플릿을 렌더링합니다.
// 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;
// main.js
import MyComponent from './component.js';
<!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>