Categories
프로그래밍

Props & Emits

Props

자식 컴포넌트에서 부모로부터 데이터를 받는 것이다.

<!-- ChildComp.vue -->
<script setup>
const props = defineProps({
  msg: String
})
</script>

자식 컴포넌트에 props 를 선언하고

<script setup>
import { ref } from 'vue'
import ChildComp from './ChildComp.vue'

const greeting = ref('부모 컴포넌트로부터 💌을 전달받았어요!')
</script>

<template>
  <ChildComp :msg="greeting" />
</template>

이렇게 부모 컴포넌트에서 자식 컴포넌트로 greeting 을 msg로 전달한다.

Emits

자식 컴포넌트는 부모로부터 props를 받는 것 뿐만 아니라 이벤트를 발송 할 수 있다.

<script setup>
// emit할 이벤트 선언
const emit = defineEmits(['response'])

// 인자와 함께 emit
emit('response', '자식 컴포넌트로부터 🌷를 받았어요!')
</script>

이렇게 자식이 발송한 response 라는 이름의 이벤트에 메시지를 실어서 보내면

<script setup>
import { ref } from 'vue'
import ChildComp from './ChildComp.vue'

const childMsg = ref('자식 컴포넌트로부터 아직 메시지를 받지 못했어요!')
</script>

<template>
  <ChildComp @response="(msg) => childMsg = msg" />
  <p>{{ childMsg }}</p>
</template>

부모에서는 이렇게 수신할 수 있다.

Slots

props 로 데이터를 전달하는 것 외에도 구성 요소는 slots 를 통해 템플릿 조각을 자식 구성 요소에 전달할 수도 있다.

By nicky8209

안녕하세요.
개발자
권동원 입니다.

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다