본문 바로가기
  • 일하면서 배운 내용 끄적이는 블로그
Vue

Slot

by dhl7799 2024. 7. 8.

Slot은 컴포넌트의 재사용성을 높여주는 기능이다.
부모 컴포넌트에서 자식 컴포넌트에 들어갈 콘텐츠를 동적으로 선언할 수 있다.

 

기본 Slot

자식 컴포넌트

<template>
  <div class="child">
    <slot></slot>
  </div>
</template>

<script>
export default {
  name: 'ChildComponent'
}
</script>

<style scoped>
.child {
  border: 1px solid #ccc;
  padding: 10px;
}
</style>

 

부모 컴포넌트

<template>
  <div class="parent">
    <child-component>
      <p>이 내용은 자식 컴포넌트에 삽입됩니다.</p>
    </child-component>
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue'

export default {
  name: 'ParentComponent',
  components: {
    ChildComponent
  }
}
</script>

<style scoped>
.parent {
  margin: 20px;
}
</style>

 

Vue 2에서 slot을 사용하여 컴포넌트 간에 유연하게 데이터를 전달하고, 동적으로 내용을 삽입할 수 있다.

Named Slot

named slot 은 여러 개의 슬롯을 구분하고, 각각의 슬롯에 다른 콘텐츠를 전달할 수 있게 함

자식 컴포넌트에서 슬롯을 정의할 때 name 속성을 사용

 

자식 컴포넌트

<template>
  <div>
    <header>
      <slot name="header"></slot>
    </header>
    <main>
      <slot></slot> <!-- 기본 슬롯 -->
    </main>
    <footer>
      <slot name="footer"></slot>
    </footer>
  </div>
</template>

 

부모 컴포넌트

<template>
  <div>
    <ChildComponent>
      <template v-slot:header>
        <h1>헤더 콘텐츠</h1>
      </template>
      <p>메인 콘텐츠</p>
      <template v-slot:footer>
        <p>푸터 콘텐츠</p>
      </template>
    </ChildComponent>
  </div>
</template>

Scoped Slot

slot이 컴포넌트 템플릿의 재사용성을 늘려주기 위한 기능이라면

scoped slot은 컴포넌트 데이터의 재사용성을 높여주는 기능이다

 

scoped slots은 자식 컴포넌트가 슬롯을 통해 부모 컴포넌트에 데이터를 전달할 수 있게 한다

이를 통해 더 복잡한 데이터 바인딩과 동작을 구현할 수 있다

 

자식 컴포넌트

<template>
  <div>
    <slot :text="message"></slot>
  </div>
</template>

<script>
export default {
  data() {
    return {
      message: 'Hello from Child Component'
    }
  }
}
</script>

 

부모 컴포넌트

<template>
  <div>
    <ChildComponent>
      <template v-slot:default="slotProps">
        <p>{{ slotProps.text }}</p>
      </template>
    </ChildComponent>
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
  components: {
    ChildComponent
  }
}
</script>

 

'Vue' 카테고리의 다른 글

디렉티브(Directives)  (0) 2024.05.08
Router push, replace, go  (0) 2024.05.08
Vuex로 중앙에서 상태 관리하기  (0) 2024.05.07
Vue 프로젝트 경로의 @  (0) 2024.05.07
emit으로 자식 -> 부모 데이터 전달  (0) 2024.05.03