vue에서 modal창을 이용하기 위해 teleport 기능을 사용하였다.
vue component는 기본적으로 App.vue 안에서 별도의 div태그로 생성된다.

그림에서 보이는 Sub1.vue는 별도의 div로 쌓여 App.vue 위에 생성되는 느낌이다.
이때 Sub1.vue가 App.vue에 있는 요소에 접근하여 태그를 생성하려고 할때, teleport 기능을 사용할 수 있다.
말 그대로 Sub1.vue에서 Sub2.vue로 텔레포트 하는 꼴로 동작하게 된다.
간단히 모달창을 띄우기 위한 코드이다.
Teleport.vue
<template>
<button @click="openModal">모달창 ON</button>
<teleport to="#modal">
<div class="black-bg" v-if="(isModal==true)">
<div class="withe-bg">
나는 모달창
</div>
</div>
</teleport>
</template>
export default {
components: {},
data() {
return {
isModal : false, // 모달창의 상태 state
}
},
methods: {
openModal(){
this.isModal = true
}
}
}
<style>
div{
box-sizing: border-box;
}
.black-bg{
width: 100vw; height: 100vh;
background-color: rgba(0,0,0,0.5);
padding: 20px;
}
.withe-bg{
width: 90%; height: 90%;
background: white;
border-radius: 8px;
padding: 20px;
}
<style>
App.vue
<template>
<div id="modal"></div>
</template>
Teleport.vue 코드를 보면 <teleport to="#modal"> 이라는 코드를 확인 할 수있다.
그 코드로 하여금 <teleport>내부 코드는 App.vue의 modal이라는 id를 가진 태그로 이동한다.
그 외, Teleport.vue 코드에서는 특정 값에 따라 모달창을 보이게/보이지 않게 하기위한 값을 통해 모달창을 제어하였다.