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>
'💻 FullStack > Vue.js' 카테고리의 다른 글
Vue 시작일과 종료일로 진행률(%) 표시하기 (0) | 2023.09.19 |
---|---|
Vue CSS height 속성 값에 % 사용해보기 (1) | 2023.09.14 |
Composition API 방식에서 refs를 쓰고싶다면 (0) | 2023.09.12 |
Vue.js 코드 작성할 수 있는 사이트 소개 (Playground) (0) | 2023.08.21 |
데이터 시각화 - Chart.js 라이브러리 (0) | 2023.08.20 |