컴포넌트-slot (#)

토리최고·2022년 1월 18일
0

Vue 문법

목록 보기
18/20
post-thumbnail

fallback contents

기본적인 content가 있으면 slot에 삽입되는데, 없으면 slot태그 사이에 있는 기본적인 내용을 출력한다. 내용이 없을때 출력되는 개념을 fallback contents라고 한다.

App.vue

<template>
  <MyBtn>
    Banana
  </MyBtn>
</template>

<script>
import MyBtn from '~/components/MyBtn'

export default {
  components: {
    MyBtn
  },
}
</script>

MyBtn.vue

<template>
  <div 
    class="btn">
    <slot>Apple</slot>
  </div>
</template>

컴포넌트 사이에있는 모든 내용이 slot태그를 대신해서 들어갈 수 있다.
하지만 순서가 바뀌면 바뀐다. 순서가 있게 하려면,

Named slot (이름을 갖는 slot)

template 태그 안에 v-slot:"icon"으로 표기해서 각자 내가 표기하고 싶은 slot에 이름을 만들어준다. 이렇게 표기해주면 순서가 뒤바뀌어도 그대로 출력된다.

App.vue

<template>
  <MyBtn>
    <template #icon>
      <span>(B)</span>
    </template>
    <template #text>
      <span>Banana</span>
    </template>
  </MyBtn>
</template>

<script>
import MyBtn from '~/components/MyBtn'

export default {
  components: {
    MyBtn
  },
}
</script>

MyBtn.vue

<template>
  <div 
    class="btn">
    <slot name="icon"></slot>
    <slot name="text"></slot>
  </div>
</template>

Slot의 약어

v-bind:로, v-on@로 표기할 수 있다.

v-slot은 다른 디렉티브들과 마찬가지로 줄일 수 있는데 #으로 약칭한다. 이렇게 약어로 쓰는게 더욱 권장된다.

0개의 댓글

관련 채용 정보