Web Components

Jian·2022년 9월 26일
0

JavaScript

목록 보기
19/27

📌 Web Components

반복되는 DOM요소를 커스텀 태그로 만들 수 있다

📌 사용법

✔️ 1. 컴포넌트 생성

<script>
    customElements.define('custom-input', Cls);

✔️ 2.클래스 만들기

<script>
**  class Cls extends HTMLElement {
        connectedCallback() {
          this.innerHTML = `<label>라벨명</label><input>`;
        }
     }**

  customElements.define('custom-input', Cls);

✔️ 3. 생성된 컴포넌트 사용하기

<body>
  <custom-input></custom-input>

📌 기능

✔️ 1.파라미터 생성 가능

<script>
  class Cls extends HTMLElement {
        connectedCallback() {
          let name = this.getAttribute('name')
          this.innerHTML = `<label>${name}</label><input>`;
        }

✔️ 2.attribute 변경 감지 가능

<script>
 class Cls extends HTMLElement {
      connectedCallback() {
        let name = this.getAttribute('name')
        this.innerHTML = `<label>${name}</label><input>`;
      }
   
      // attr 변경 감지 가능. name 속성 변경됨을 감지한다.
      static get observedAttributes() {
        return ['name']
      }
      // 변경 감지 시 실행할 코드
      attributeChangedCallback() {
        console.log('sdf')
      }
    }
<body>
  <custom-input name='ID'></custom-input>
profile
개발 블로그

0개의 댓글