[Vue3] Teleport

ChanSol Jeong·2023년 7월 3일
0

Vue

목록 보기
5/6
post-thumbnail

Vue에는 Teleport라는 신기한 기능이 있다!

<body>
  <div style="position: relative;">
    <h3>Tooltips with Vue 3 Teleport</h3>
    <div>
      <modal-button></modal-button>
    </div>
  </div>
</body>
<script setup>
import { ref } from "vue";

const modalOpen =  ref(false); 
</script>
<template>
  <button @click="modalOpen = true">
        Open full screen modal!
  </button>
  <div v-if="modalOpen" class="modal">
    <div>
      I'm a modal!
        <button @click="modalOpen = false">
          Close
        </button>
    </div>
  </div>
  </template>

다음과 같이 구성된 Vue에서 modal-button의 위치는 html>div>div 안쪽에 있다.

하지만 다음과 같이 teleport 태그를 사용하면 신기한 현상이 발생한다.

<body>
  <div style="position: relative;">
    <h3>Tooltips with Vue 3 Teleport</h3>
    <div>
      <teleport to="body">
        <modal-button></modal-button>
      </teleport>
    </div>
  </div>
</body>

실제 렌더링

<body>
  <div style="position: relative;">
    <h3>Tooltips with Vue 3 Teleport</h3>
    <div>
    </div>
  </div>
  <modal-button></modal-button>
</body>

teleport 태그를 이용하여 body로 보내라는 명령에 따라서 teleport 내부의 태그들은 body로 이동한다.

teleportVue에서 modal을 구현할때 굉장히 유용하게 사용할 수 있다.

profile
Compostion API 맛있다!

0개의 댓글