54. Named Slots

npm create vue@latest


이 강의에서는 컴포넌트 파일에서 명명된 슬롯(named slots)을 사용하는 방법을 배우게 됩니다.
요약하면 다음과 같습니다:

  1. 슬롯은 부모 컴포넌트에서 자식 컴포넌트로 콘텐츠를 전달하는 데 사용됩니다.
    이를 통해 하나의 컴포넌트를 뼈대(skeleton)처럼 사용하여 여러 곳에서 재사용할 수 있습니다.
  2. 예제에서는 App 컴포넌트에 두 개의 폼을 만들고 각기 다른 내용을 전달합니다.
  3. Form 컴포넌트에는 slot 태그를 사용하여 부모 컴포넌트에서 전달된 콘텐츠가 렌더링될 위치를 지정합니다.
  4. 명명된 슬롯을 사용하여 콘텐츠를 더 잘 배치할 수 있습니다.
    예를 들어, Form 컴포넌트에는 도움말, 필드, 버튼 섹션에 각각 다른 이름의 슬롯을 할당합니다.
  5. App 컴포넌트에서는 v-slot(#) 지시어를 사용하여 각 섹션의 콘텐츠를 해당 슬롯에 매핑합니다. v-slot 지시어는 template 태그에만 적용됩니다.
  6. 명명된 슬롯과 기본 슬롯(default slot)을 함께 사용할 수 있으며, 기본 슬롯은 특정 슬롯에 할당되지 않은 콘텐츠가 들어갈 위치입니다.
  7. 슬롯을 사용하면 부모 컴포넌트의 데이터를 자식 컴포넌트의 슬롯 콘텐츠 내에서 사용할 수 있습니다. 이 경우 props를 사용하지 않고도 데이터를 전달할 수 있습니다.

이 강의를 통해 슬롯을 사용하여 콘텐츠를 더 효율적으로 관리하고, 컴포넌트를 재사용하는 방법을 배웠습니다.

App.vue
<script lang="ts">
   import AppForm from '@/components/Form.vue'
   export default {
      name: 'App',
      components: {
         AppForm,
      },
      data() {
         return {
            help: 'This is some help text.',
         }
      }
   }
</script>

<template>
   <AppForm>
      <template #help>
         <p>{{ help }}</p>
      </template>
      <template #fields>
         <input type="text" placeholder="email">
         <input type="text" placeholder="username">
         <input type="text" placeholder="password">
      </template>
      <template #buttons>
         <button type="submit">Submit</button>
      </template>
      <p>Dummy Text</p>
   </AppForm>

   <AppForm>
      <template #help>
         <p>{{ help }}</p>
      </template>
      <template #fields>
         <input type="text" placeholder="email">
         <input type="text" placeholder="username">
      </template>
      <template #buttons>
         <button type="submit">Submit</button>
      </template>
   </AppForm>
</template>