svelte 에서 slot이란 뭘 하는 녀석일까?

YunKuk Park·2022년 2월 4일
0

svelte

목록 보기
3/5
post-thumbnail

💡 svelte kit을 이용해 전체적인 레이아웃을 만드는데 <slot> 이라는 이상한 태그를 만났다.
__layout.svelte 에서 사용한 태그인데 <slot>은 어떤 것을 하기 위해 있는 태그일까?

// src/routes/__layout.svelte
<script>
  import '../reset.css';
  import '../app.css';
</script>

<slot />

Slot

HTML 요소는 자식 요소를 가질 수 있다.

컴포넌트도 slot 을 사용하면 자식 요소를 가질 수 있게 된다.

예제 코드

// src/lib/FormLayout.svelte
<form>
  <header>
    <Logo />
  </header>
  <slot />
</form>

// Form.svelte
<script>
  import FormLayout from '$lib/FormLayout.svelte';
</script>

<FormLayout>
  <h1>로그인해라.</h1>
  <form class="user-form" on:submit|preventDefault={onSubmit}>
    <input type="text" bind:value={userInfo.id}/>
	<input type="password" bind:value={userInfo.password}/>		
    <button>폭발</button>
  </form>
</FormLayout>

Form.svelte<FormLayout> 의 자식 요소들이 FormLayout.svelte<slot> 위치에 들어가게 된다.

Slot Fallbacks

컴포넌트의 slot 요소 안에 값이 비어있다면 인자에 default 값을 주듯이 fallback 을 지정할 수 있다.

fallback: (만약의 경우에) 의존할 사물

예제 코드

// Box.svelte
<div class="box">
  <slot>
	<em>아무것도 안들어왔어요</em>
  </slot>
</div>

//App.svelte
<script>
  import Box from './Box.svelte';
</script>

<Box>
  <h2>Hello!</h2>
  <p>This is a box. It can contain anything.</p>
</Box>

<Box/>

Named slots

배치에 대한 더 많은 제어가 필요 할 수 있는데, 이런 경우 Named slot 을 사용할 수도 있다.

ContactCard.svelte 에서 각 슬롯에 name 특성을 추가한다.

이렇게

<article class="contact-card">
  <h2>
  	<slot name="name">
  	  <span class="missing">Unknown name</span>
  	</slot>
  </h2>

  <div class="address">
    <slot name="address">
      <span class="missing">Unknown address</span>
    </slot>
  </div>
  
  <div class="email">
    <slot name="email">
      <span class="missing">Unknown email</span>
    </slot>
  </div>
</article> 

그리고 불러오는 부모에게 다음과 같이 지정해준다.

<script>
	import ContactCard from './ContactCard.svelte';
</script>

<ContactCard>
  <span slot="name">
	P. Sherman
  </span>

  <span slot="address">
	42 Wallaby Way<br>
	Sydney
  </span>

  <span slot="email">
	hihi@gmail.com
  </span>
</ContactCard>

slot=”..” 을 통해서 slot name 에서 설정한 값을 넣어 엮어준다.

Checking for slot content $$slots

경우에 따라 상위 항목이 특정 슬롯에 대한 내용을 전달하는지 여부에 따라 구성 요소의 일부를 제어 할 수 있다.

checking slot 을 하지 않았을 때

checking slot 을 했을 때

// class 에 조건을 걸고 싶을 때
<article class:has-discussion={$$slots.comments}> </article>

// html 에 조건을 걸고 싶을 때
{#if $$slots.comments}
	<div class="discussion">
		<h3>Comments</h3>
		<slot name="comments"></slot>
	</div>
{/if}

$$slot.slotName 으로 접근 하여 slot content 를 check 한다.

profile
( • .̮ •)◞⸒⸒

1개의 댓글

comment-user-thumbnail
2024년 3월 13일

In summation, Codice Fiscale stands as a linchpin of Italy's administrative framework, bridging the gap between individuals and the myriad institutions they interact with on a daily basis. Mastery of its intricacies empowers individuals and entities https://calcola-codice-fiscale.it/ to navigate the labyrinth of bureaucracy with ease, ensuring seamless interaction and compliance with regulatory requirements.

답글 달기