Vue DefineEmit & DefineProps

Yeeun_Kim·2024년 3월 22일
0
post-thumbnail

Props & Emit (Component Communication)

1) Props

  • 상위 컴포넌트에서 하위 컴포넌트로 데이터 전달을 위해 사용된다.

2) Emit

  • 하위 컴포넌트에서 상위 컴포넌트로 이벤트 전달을 위해 사용된다.

사용 예시

App.vue: 부모 컴포넌트

<template>
    <div>Counter: {{ count }}</div>
    <counter
        :count-value="2"
        @increase="increase"
        @decrease="decrease"
    ></counter>
</template>

<script setup>
import { ref } from "vue";
import Counter from "./components/Counter.vue";

const count = ref(0);

const increase = (value) => {
    count.value += value;
};

const decrease = (value) => {
    count.value -= value;
};
</script>

Counter.vue: 자식 컴포넌트

<template>
    <button type="button" @click="onIncrease">+</button>
    <button type="button" @click="onDecrease">-</button>
</template>

<script setup>
const props = defineProps(['countValue'])

const emit = defineEmits(["increase", "decrease"]);

const onIncrease = () => {
    emit("increase", props.countValue);
};
const onDecrease = () => {
    emit("decrease", props.countValue);
};
</script>

해당 코드는 서로 데이터가 잘 오고 가는지 확인하기 위하여 간단한 Counter를 구현해본 것이다.
부모 컴포넌트에서 준 값 props을 자식 컴포넌트는 다시 emit으로 이벤트 요청을 보내는 간단한 코드를 구현해 보았다.

활용

App.vue: 부모 컴포넌트

<template>
    <div>Text: {{ text }}</div>
    <TextField v-model="text"></TextField>
</template>

<script setup>
import { ref } from "vue";
import TextField from "./components/TextField.vue";

const text = ref("");
</script>

TextField.vue: 자식 컴포넌트

<template>
    <input
        type="text"
        :value="modelValue"
        @input="$emit('update:modelValue', $event.target.value)"
    />
</template>

<script setup>
defineProps(["modelValue"]);
defineEmits(["update:modelValue"]);
</script>

해당 코드는 TextField 컴포넌트를 공통으로 사용 가능하게 하는 코드로 TextField에서 입력 받는 값을 부모 컴포넌트에 넘길 수 있다.

2개의 댓글

comment-user-thumbnail
2024년 3월 26일

이번 기회에 Vue의 부모 Component와 자식 Component의 데이터 전달에 대해 좋은 이해가 되었습니다. 감사합니다.

답글 달기
comment-user-thumbnail
2024년 3월 26일

하위 컴포넌트와 상위 컴포넌트에 대한 관계를 더욱 알게 되었습니다. 감사합니다.

답글 달기