민우의 코딩일지
article thumbnail

OptionsAPI와 차이점

OptinosAPI 방식에서 사용했던 props , $emit의 사용방법 그대로,  CompositionAPI 방식에서 사용해보면 에러가 발생한다 😥

왜냐면,  CompositionAPI 방식에선 defineProps, defineEmtis를 이용하도록 방법이 바뀌었기때문이다 .. !

defineEmits 관련 자료는 찾기가 어려워서 간단히 예시를 포스팅해보았다 ( 하는김에 defineProps도 같이 .. )

 

 

 

 

 

 

 

 

 

 

 

 


 

 

 

 

 

 

 

 

 

 

 

defineProps

부모 컴포넌트

<template>
    <div>
        <!-- props 전달하는 방식은 OptionsAPI 방식과 동일 -->
        <ChildComponent 
         :data="parentData" 
        />
    </div>
</template>

<script setup>
import ChildComponent from '.vue파일의 경로와 이름'
const parentData="부모데이터"
</script>

자식 컴포넌트

<template>
    <div>
        <p>Composition API 방식으로 Props 사용해보기</p>
        <p>받은 내용 =>  {{ data }}</p>
    </div>
</template>

<script setup>
// defineProps를 이용해서 데이터를 받을 수 있다..!
const props = defineProps({
    // 변수명 : 타입(Number,String,Array,Object..)
    data : Object
})
</script>

 

 

 

 

 

 

 

 

 

 


 

 

 

 

 

 

 

 

 

 

 

defineEmits

부모 컴포넌트

<template>
    <div>
       <!-- 부모 컴포넌트에서 emit 처리하는 방법은 기존 OptionsAPI 방식과 동일 -->
        <ChildComponent 
            @showAlertOne="functionOne" 
            @showAlertTwo="functionTwo" 
        />
        
    </div>
</template>

<script setup>
import ChildComponent from '.vue파일의 경로와 이름'

const functionOne = () => { 
    alert("자식 컴포넌트에서 emits('showAlertOne')을 사용했기에 호출된 함수'"); 
}
const functionTwo = (param) => { 
    alert("자식 컴포넌트에서 에밋을 사용하며, 함께 보낸 데이터 => " + param); 
}
</script>

자식 컴포넌트

<template>
    <div>
        <button @click="btnEventOne">emit 사용( 데이터 전달 x )</button>
        <button @click="btnEventTwo">emit 사용( 데이터 전달 o )</button>    
    </div>
</template>

<script setup>
// [] 배열형태로 emit 이름들을 저장하는 변수
const emits = defineEmits(["showAlertOne", "showAlertTwo"]);


// 매개변수 전달 x
const btnEventOne = () => {
    emits('showAlertOne');
}

// 매개변수 전달 o
const btnEventTwo = () => {
    emits('showAlertTwo', '전달하고싶은 데이터');
}
</script>