🧩 Vue 컴포넌트란?

정의

Vue 컴포넌트는 화면을 구성하는 독립적인 UI 단위다.

컴포넌트는 재사용성을 높이고, 화면을 역할별로 나누는 데 유용하다.

🔁 컴포넌트 간 통신

  • Vue에서는 기본적으로 부모에서 자식으로 데이터가 내려간다.
  • 자식은 부모에게 이벤트를 보내는 방식으로 통신한다.
  • 단방향 데이터 흐름을 유지하면 구조가 더 예측 가능해진다.

image

📦 Props

  • 부모의 데이터를 자식에게 전달할 때 사용한다.
  • 자식은 props를 직접 수정하지 않는다.

defineProps

<script setup>
defineProps(["myMsg"]);
</script>
<script setup>
defineProps({
  myMsg: String,
});
</script>

Parent 사용 예시

<template>
  <Child my-msg="message" />
</template>

📣 emit

  • 자식 컴포넌트가 부모에게 이벤트를 전달할 때 사용한다.
  • $emit 또는 defineEmits로 선언한다.

defineEmits

<script setup>
const emit = defineEmits(["updateNameToParent"]);

const onUpdateName = (name) => {
  emit("updateNameToParent", name);
};
</script>

부모에서 받기

<template>
  <Child @update-name-to-parent="changeName" />
</template>

🛠️ 사용 예시

부모

<template>
  <Child :my-msg="message" @update-name-to-parent="changeName" />
</template>

자식

<template>
  <button @click="$emit('updateNameToParent', 'newName')">emit</button>
</template>

⚠️ 주의점

  • props는 자식이 직접 바꾸지 않는다.
  • 이벤트 이름은 일관성 있게 작성한다.
  • 부모와 자식의 책임을 분리하면 유지보수가 쉬워진다.

📌 정리

  • Vue 컴포넌트는 재사용 가능한 UI 단위다.
  • props는 부모에서 자식으로, emit은 자식에서 부모로 흐른다.
  • defineProps, defineEmits를 먼저 익히면 구조를 이해하기 쉽다.

연결문서

댓글남기기