Slot

Joey·2024년 12월 1일

Slot?

<slot>웹 컴포넌트(Web Components)에서 사용되는 중요한 요소로, 컴포넌트 내에서 외부 콘텐츠를 삽입할 수 있는 자리표시자(placeholder) 역할을 합니다.

<slot>Shadow DOM과 함께 사용되어, 외부 콘텐츠를 Shadow DOM 내부에 삽입할 수 있도록 도와줍니다. 이를 통해 컴포넌트의 재사용성과 캡슐화가 강화됩니다.

<my-element>
  <h1>External Heading</h1>
  <p>This is an external paragraph.</p>
</my-element>

<script>
  class MyElement extends HTMLElement {
    constructor() {
      super();
      this.attachShadow({ mode: 'open' });

      this.shadowRoot.innerHTML = `
        <style>
          h1 {
            color: green;
          }
          p {
            color: blue;
          }
        </style>
        <div>
          <h2>Internal Heading</h2>
          <slot></slot>  <!-- 외부 콘텐츠가 이곳에 삽입됨 -->
        </div>
      `;
    }
  }

  customElements.define('my-element', MyElement);
</script>

<my-element> 내부의 <h1><p>Shadow DOM 내의 <slot> 위치에 삽입됩니다.
External HeadingThis is an external paragraph.Shadow DOM 내에서 <slot> 위치로 삽입됩니다.
내부에서 정의한 Internal Heading은 Shadow DOM 내부에서 그대로 렌더링됩니다.

Slot의 종류

1. 기본 슬롯
기본 슬롯은 이름이 없으며, 외부 콘텐츠가 없을 때 기본 콘텐츠를 삽입할 수 있습니다.

<template>
  <div>
    <slot>Default Content</slot> <!-- 콘텐츠가 없으면 기본 콘텐츠 사용 -->
  </div>
</template>

2. 이름이 있는 슬롯
이름을 가진 슬롯을 사용하면, 특정 콘텐츠를 특정 슬롯에 할당할 수 있습니다.

<my-element>
  <h1 slot="header">Header Content</h1>
  <p slot="body">Body Content</p>
</my-element>

<script>
  class MyElement extends HTMLElement {
    constructor() {
      super();
      this.attachShadow({ mode: 'open' });
      this.shadowRoot.innerHTML = `
        <style>
          h1 {
            color: red;
          }
          p {
            color: blue;
          }
        </style>
        <div>
          <slot name="header"></slot> <!-- 'header'라는 이름을 가진 슬롯 -->
          <slot name="body"></slot>   <!-- 'body'라는 이름을 가진 슬롯 -->
        </div>
      `;
    }
  }

  customElements.define('my-element', MyElement);
</script>

<h1 slot="header">Header Content</h1>header라는 이름의 슬롯에 삽입됩니다.

<p slot="body">Body Content</p>body라는 이름의 슬롯에 삽입됩니다.
각각의 슬롯은 name 속성에 의해 구분됩니다.

3. ::slotted CSS 선택자
::slotted()는 슬롯 내에서 삽입된 외부 콘텐츠에 스타일을 적용할 때 사용합니다.
Shadow DOM 내부에서 외부 콘텐츠에 스타일을 지정할 수 있습니다.

<my-element>
  <h1>This is a header</h1>
  <p>This is a paragraph</p>
</my-element>

<script>
  class MyElement extends HTMLElement {
    constructor() {
      super();
      this.attachShadow({ mode: 'open' });
      this.shadowRoot.innerHTML = `
        <style>
          ::slotted(h1) {
            color: red;
          }
          ::slotted(p) {
            font-size: 14px;
          }
        </style>
        <div>
          <slot></slot>
        </div>
      `;
    }
  }

  customElements.define('my-element', MyElement);
</script>

<h1><p>::slotted 선택자에 의해 Shadow DOM 내에서 스타일을 적용받습니다.
h1은 빨간색, p는 글꼴 크기가 14px로 설정됩니다.

profile
멋쟁이사자처럼 프론트엔드 부트캠프 12기

0개의 댓글