카테고리 없음
Vue3 Composition API와 기초 문법 다뤄보기(3)
xhakxh135
2024. 3. 22. 15:37
반응형
SMALL
12. props
자식 컴포넌트를 props를 통해 부모로부터 데이터를 받을 수 있다.
가장 먼저 해야할 것은 자식 컴포넌트에 허용할 props를 선언하는 것이다.
<script setup>
const props = defineProps({
msg:String
})
</script>
defineProps()가 선언되면 msg는 프롭스를 자식 컴포넌트에서 사용할 수 있다.
defineProps에서 반환된 객체는 자바스크립트에서 접근할 수 있다.
부모는 속성을 사용하는 것 처럼 자식에게 프롭스를 전달 할 수 있다.
동적인 값을 전달하기 위해 v-bind 문법을 사용할 수 도 있다.
<ChildComp :msg="greeting" />
<!--------App.vue----------->
<script setup>
import {ref} from 'vue'
import ChildComp from './ChildComp.vue'
const greeting = ref('부모 컴포넌트로부터 prop를 전달 받았습니다.')
</script>
<template>
<ChildComp v-bind:msg="greeting"/>
</template>
<!--------App.vue----------->
<!--------ChildComp.vue----------->
<script setup>
const props = defineProps({
msg:String //나는 msg를 스트링 타입으로 전달하겠다.
})
<script/>
<template>
<h1>{{msg || 'prop이 아직 전달되지 않았습니다.'}}</h1>
</template>
<!--------ChildComp.vue----------->
13.emits
emits은 props와 반대로 자식이 부모에게 이벤트를 전달 할 수 있다.
우선 전달할 이벤트를 emits으로 선언한다.
<script setup>
const emit = defineEmits(['response']) // emit할 이벤트를 선언한다.
emit(['response', '자식 컴포넌트로부터 emit을 받았어요.']) //인자와 함께 emit 전달
</script>
emit()의 첫번째 인자는 이벤트의 이름이다. 이후 추가되는 모든 인자는 이벤트 리스너에 전달된다.
부모는 v-on을 사용하여 자식이 보낸 이벤트를 수신할 수 있다.
<ChildComp @response="(msg) => childMsg = msg" />
예제 코드)
<!--------App.vue----------->
<script setup>
import {ref} from 'vue'
import ChildComp from './ChildComp.vue'
const childMsg = ref('자식 컴포넌트로 부터 아직 emits을 받지 못 했어요.')
</script>
<template>
<ChildComp @response = "(msg) => childMsg = msg" />
<p>{{childMsg}}</p>
</template>
<!--------App.vue----------->
<!------ChildComp.vue-------->
<script setup>
const emits = defineEmits(['response']) //emits 선언
emit('response', '자식 컴포넌트로 부터 emits을 받았어요.')
<script/>
<template>
<h1>자식 컴포넌트</h1>
</template>
<!------ChildComp.vue-------->
14.slot
부모 컴포넌트는 자식에게 데이터를 전달하는 외 에도 슬롯을 사용하여 템플릿 조각을 전달 할 수 있다.
자식 컴포넌트가 부모에게 보내고자 하는 템플릿 조각을 <slot></slot>으로 사용하면 렌더링이 가능하다.
<!--부모 템플릿에서-->
<ChildComp>
이 곳은 슬롯 컨텐츠 입니다.
</ChildComp>
<!--자식 템플릿에서-->
<slot/>
slot은 "대체"라고 생각하면 된다.
예제 코드)
<!----------App.vue---------->
<script setup>
import { ref } from 'vue'
import ChildComp from './ChildComp.vue'
const msg = ref('Vue는 개발자에게 정말 유용하죠!')
</script>
<template>
<ChildComp>부모로부터{{msg}}</ChildComp>
</template>
<!----------App.vue---------->
<!--------ChildComp.vue-------->
<script setup>
import { ref } from 'vue'
</script>
<template>
<slot>부모로 부터 아직 컨텐츠를 못 받았어요.</slot>
</template>
<!--------ChildComp.vue-------->
반응형
LIST