Web Components : 커스텀 HTML 태그

재웅·2023년 4월 17일
0

오늘의 정리

목록 보기
14/52
post-thumbnail

HTML 반복되는 부분 많고 드러울때 사용함

여러개의 <div> 태그들을 하나의 단어로 축약할 수 있는 문법임

커스텀 html 태그 만드는법

<custom-input> 이라고 입력하면

<label><input> 이렇게 2개의 태그가 안에 출현하게 만들고 싶다면?

class 클래스 extends HTMLElement {

   connectedCallback() {
      this.innerHTML = '<label>이름을 입력하쇼</label><input>'
   }
}

customElements.define("custom-input", 클래스);
  

<custom-input> 같은 커스텀 태그를 컴포넌트라고 함

1. 컴포넌트에 어떤 html들을 집어넣을지 맘대로 설정 쌉가능

class와 extend 문법 저렇게 그대로 써주시면 되고 (class명 작명가능)

안에는 connectedCallback() 이라는 함수안에 

여러분의 커스텀 html을 막 꾸미면 됨

(참고) connectedCallback() 함수는 컴포넌트가 html에 장착될 때 실행

 

 

2. html 만들고 싶으면 쌩자바스크립트로 html 만드는 문법 가져다 쓰면 됨

 

3. customElements.define() 처럼 써주면 컴포넌트 등록이 쌉가능

**(컴포넌트 이름 작명시 - 기호 무적권 들어가야됨)**

<custom-input> 이라고 쓸 때마다 <label> <input> 남음


attribute를 추가 => 각각 다른 내용을 보여줄 수 있음

class 클래스 extends HTMLElement {

   connectedCallback() {
      let name = this.getAttribute('name'); // attribute 추가
      this.innerHTML = '<label>${name}을 입력하쇼</label><input>'
   }
}

customElements.define("custom-input", 클래스);
<custom-input name="이메일"></custom-input> 
<custom-input name="비번"></custom-input>

<custom-input name="비번"></custom-input> 이렇게 쓰면 "비번을 입력하쇼"

<custom-input name="이메일"></custom-input> 이렇게 쓰면 "이메일을 입력하쇼"


attribute가 변경될 때 특정 코드 실행도 가능

React, Vue에서 제공하는 자동 html 재렌더링 기능도 쌩 자바스크립트만으로 구현가능

class 클래스 extends HTMLElement {

   connectedCallback() {
      let name = this.getAttribute('name');
      this.innerHTML = '<label>${name}을 입력하쇼</label><input>'
   }

   static get observedAttributes() {
       return ['name']
   }
   attributeChangedCallback() {
       (attribute 변경시 실행할 코드)
   }
}

customElements.define("custom-input", 클래스);

static get observedAttributes() 안에 감시할 attribute들을 array로 쓰면됨

그럼 그게 변경되는 순간 밑에 있는 attributeChangedCallback() 함수를 실행해줌

profile
오늘의 정리

0개의 댓글