데일리 공부 기록

hands on vue3 - 원하는 요소에 붙여넣는 teleport tag에 대한 연습

탐훈 2023. 3. 12. 17:29
728x90

[목표]

1. App.vue -> ManageGoals.vue -> ErrorAlert.vue 상속구조다 

예를 들어 제일 아래의 자식에서 만든 엘레멘트를 Body에 붙이고 싶다면?

 

고것이 바로 teleport 태그다.. 

 

전 포스팅에서 소스를 가져와 

다음 연습문제를 풀어보도록

 

Q. Modal창으로 사용자에게 알려준 error-alert를 

body에 붙이도록 하라. 

현재 ManageGoals.vue 안에 error-alert 태그가 입력되어 있다.

이렇게 되면 body -> App -> ManageGoals 안에 error-alert 태그가 있는 셈이다.

원하는 목표는 body 안에 error-alert이 있어야한다. 

 

dialog 태그가 여러개의 div 안에 들어가 있다. body 밑으로 빼보기


[ManageGoals.vue]

<template>
  <div>
    <h2>Manage Goals</h2>
  </div>
    <input type="text" ref="inputGoal">  
    <button @click="setGoal">SetGoals</button> 
  <div>
    <teleport to="body">
      <error-alert @closeModal="closeModal" v-if="isError==true">
        <p>내용을 입력해주세요!</p>
      </error-alert>
    </teleport>
  </div>
</template>

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

export default {
  components:{
    ErrorAlert,
  },
  data(){
    return{
      isError: false,
    }
  },
  methods:{
    closeModal(){
      this.isError = false;
    },
    setGoal(){
      const inputData = this.$refs.inputGoal;
      console.log(inputData.value);
      if(!inputData.value){
        this.isError = !this.isError;
      }
    }
  }
}
</script>

<style>

</style>

body 밑으로 적용한 결과

굉장히 쉽다.

아래 코드처럼만 하면 된다.

 

<teleport to="아이디 혹은 클래스 혹은 엘레멘트 이름 넣기">



</teleport>

 

body가 아니고 

ID값으로 userId로 하려면 어떻게 해야될까?

<teleport to="#userId">



</teleport>