LWC Slot 사용하기

ahncheer·2022년 9월 2일
0

LWC & LWR

목록 보기
11/45

● Slot이란?

  • HTML slot 요소는 웹 컴포넌트 사용자가 자신만의 마크업으로 채워 별도의 DOM 트리를 생성하고, 컴포넌트와 함께 표현할 수 있는 웹 컴포넌트 내부의 플레이스홀더입니다.
    출처 > slot

● 기본 구조 미리보기

● 코드 작성 후 확인

1) 코드 작성

※ lwc011SlotParent.html

<template>
    <div class="wrap">
        <c-lwc012-slot-child>
            <span slot="firstSlot">(부모lWC)firstName</span>
            <span slot="secondSlot">
                <div class="second-slot-wrap">
                    <h5>SecondSlot-Parent</h5>
                    <p>부모 LWC에서 작성했습니다.</p>
                </div>
            </span>
            <span slot="thirdSlot"></span>
            <span>이름 없는 slot</span>
        </c-lwc012-slot-child>
    </div>
</template>

※ lwc011SlotParent.css

.wrap{
    width: 100%;
    max-width: 800px;
    min-height: 200px;
    margin: 10px auto;
    padding: 10px;
    position: relative;
    background-color: #FFF;
    border-radius: 10px;
}
.second-slot-wrap{
    width: 200px;
    padding: 5px 10px;
    background-color: antiquewhite;
    border: 1px solid #ddd;
    border-radius: 10px;
}

※ lwc012SlotChild.html

<template>
    <div class="wrap">
        <p>firstSlot → <slot name="firstSlot">Default first name</slot></p>
        <p>secondSlot → <slot name="secondSlot">Default last name</slot></p>
        <p>thirdSlot → <slot name="thirdSlot">Default content</slot></p>
        <p>noNameSlot → <slot>Default description</slot></p>
    </div>
</template>

※ lwc012SlotChild.css

.wrap p{
    width: 100%;
    padding: 10px;
    background-color: #dee0e9;
    margin: 10px 0;
    border-radius: 10px;
}

2) 화면 확인

  • slot을 사용해 자식 컴포넌트에 들어갈 내용을 부모 컴포넌트에서 작성 할 수 있다.
  • 부모 컴포넌트에서 자식 컴포넌트로 데이터를 옮기는 번거로움이 줄어든다.
  • slot으로 불러오면 부모 컴포넌트에서 지정한 CSS가 적용되어 있기 때문에 CSS를 중복으로 작성하거나, 부모 CSS파일을 import를 하지 않아도 된다.

참고한 Slot 예제 > Pass Markup into Slots

profile
개인 공부 기록용.

0개의 댓글