
부모 -> 자식
Parent.vue
<template>
<ChildComponent message="안녕하세요!" />
</template>
<script>
import ChildComponent from './ChildComponent.vue'; // 자식 컴포넌트 임포트
export default {
components: { ChildComponent }, // 자식 컴포넌트를 등록
};
</script>
ChildComponent.vue
<template>
<p>{{ message }}</p> // 전달받은 props를 화면에 표시
</template>
<script>
export default {
// 부모로부터 받을 props를 정의
props: {
message: String,
},
};
</script>
자식 -> 부모
ChildComponent.vue
<template>
<button @click="sendData">데이터 보내기</button>
</template>
<script>
export default {
methods: {
sendData() {
// 'customEvent'라는 이벤트를 발생시키고 데이터를 전달
this.$emit('customEvent', '안녕하세요!');
},
},
};
</script>
Parent.vue
<template>
<ChildComponent @customEvent="handleData" />
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: { ChildComponent },
methods: {
handleData(message) {
console.log('받은 메시지:', message);
},
},
};
</script>
customEvent 듣고 있기(@customEvent="handleData")
이벤트 발생 -> handleData 메서드 실행 -> 전달받은 메시지 처리
Component 간 데이터 전송
Mitt: Vue의 외부 라이브러리 / 이벤트 버스를 구현하여 Component 간 데이터 전송
Vue 앱의 상태를 중앙에서 관리하는 라이브러리
vue create data-transfer-practice3가지 컴포넌트 파일 생성

최상위 파일인 App.vue에서 ParentComponent를 등록해서 화면에 표시되도록 설정
<template>
<img alt="Vue logo" src="./assets/logo.png">
<HelloWorld msg="Welcome to Your Vue.js App"/>
</template>
<script>
import HelloWorld from './components/ParentComponent.vue'
export default {
name: 'App',
components: {
HelloWorld
}
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
데이터 관리 / 자식 컴포넌트와의 연결 고리 역할
<template>
<div>
<h1>부모 컴포넌트</h1>
<!-- 자식 A 컴포넌트 -->
<ChildA @send-result="updateResult" />
<!-- 자식 B 컴포넌트 -->
<ChildB :result="result" />
</div>
</template>
<script>
import ChildA from './ChildA.vue';
import ChildB from './ChildB.vue';
export default {
components: {
ChildA,
ChildB,
},
data() {
return {
result: '', // A 컴포넌트에서 받은 데이터를 저장
};
},
methods: {
updateResult(value) {
this.result = value; // 자식 A로부터 받은 데이터를 result에 저장
},
},
};
</script>
<ChildA @send-result="updateResult" />
<ChildB :result="result" />
:result="result"export default{}
components: {}
data(){ return { result: '' } }
methods: { updateResult(value) { ... } }
<template>
<div>
<h2>자식 A 컴포넌트</h2>
<button @click="sendData('O')">O</button>
<button @click="sendData('X')">X</button>
</div>
</template>
<script>
export default {
methods: {
sendData(value) {
// 'send-result'라는 이벤트를 부모에게 전달
this.$emit('send-result', value);
},
},
};
</script>
<button @click="sendData('O')">0
methods: {}
sendData(value)
<template>
<div>
<h2>자식 B 컴포넌트</h2>
<p>결과: {{ result }}</p>
</div>
</template>
<script>
export default {
props: {
result: {
type: String, // 문자열 타입
required: true, // 필수 props
},
},
};
</script>
<p>결과: {{ result }}</p>
props: {}: 부모 컴포넌트로부터 받을 데이터 정의
result: {type: String, required: true}


Mitt로 ChildA에서 발생한 데이터를 ChildB로 전송
ㄴ 이때 부모 컴포넌트를 거치지 않음!
npm install mitt
// src/eventBus.js
import mitt from 'mitt';
const eventBus = mitt(); // Mitt 객체 생성
export default eventBus; // 다른 파일에서 사용할 수 있도록 export[ParentComponent.vue]
<template>
<div>
<h1>Mitt 사용 예제</h1>
<!-- 자식 A 컴포넌트 -->
<ChildA />
<!-- 자식 B 컴포넌트 -->
<ChildB />
</div>
</template>
<script>
import ChildA from './ChildA.vue';
import ChildB from './ChildB.vue';
export default {
components: {
ChildA,
ChildB,
},
};
</script>
[ChildA.vue]
<template>
<div>
<h2>자식 A 컴포넌트</h2>
<button @click="sendData('O')">O</button>
<button @click="sendData('X')">X</button>
</div>
</template>
<script>
import eventBus from '../eventBus.js'; // Mitt 이벤트 버스 가져오기
export default {
methods: {
sendData(value) {
// 'custom-event'라는 이벤트와 데이터를 발생시킴
eventBus.emit('custom-event', value);
},
},
};
</script>
[ChildB.vue]
<template>
<div>
<h2>자식 B 컴포넌트</h2>
<p>결과: {{ result }}</p>
</div>
</template>
<script>
import eventBus from '../eventBus.js'; // Mitt 이벤트 버스 가져오기
export default {
data() {
return {
result: '', // 수신한 데이터를 저장할 변수
};
},
mounted() {
// 'custom-event'를 수신하고 데이터 처리
eventBus.on('custom-event', (value) => {
this.result = value; // 데이터를 result에 저장
});
},
};
</script>
=> Mitt는 데이터를 중앙에서 관리하고, 앱 전체에서 컴포넌트들이 데이터를 쉽게 주고받을 수 있는 이벤트 허브 역할을 함
특정 컴포넌트 간 제한 없이 자유롭게 데이터를 전달하거나 수신할 수 있는 점이 가장 큰 강점!


Vuex: Vue의 중앙 상태 관리 도구
Mitt와 달리 데이터를 중앙 Store에서 관리 -> 모든 컴포넌트가 이 데이터를 공유
npm install vuex@4
Store 생성
// src/store/index.js
import { createStore } from 'vuex';
const store = createStore({
state: {
result: '', // 공유할 데이터
},
mutations: {
updateResult(state, payload) {
state.result = payload; // result 값을 업데이트
},
},
actions: {
setResult({ commit }, payload) {
commit('updateResult', payload); // mutations 호출
},
},
getters: {
getResult(state) {
return state.result; // result 값 반환
},
},
});
export default store;
Store 등록 in src/main.js
import { createApp } from 'vue';
import App from './App.vue';
import store from './store'; // Store 가져오기
const app = createApp(App);
app.use(store); // Vue 앱에 Store 등록
app.mount('#app');
[ParentComponent.vue]
<template>
<div>
<h1>Vuex 사용 예제</h1>
<!-- 자식 A 컴포넌트 -->
<ChildA />
<!-- 자식 B 컴포넌트 -->
<ChildB />
</div>
</template>
<script>
import ChildA from './ChildA.vue';
import ChildB from './ChildB.vue';
export default {
components: {
ChildA,
ChildB,
},
};
</script>
[ChildA.vue]
<template>
<div>
<h2>자식 A 컴포넌트</h2>
<button @click="sendData('O')">O</button>
<button @click="sendData('X')">X</button>
</div>
</template>
<script>
import { mapActions } from 'vuex';
export default {
methods: {
...mapActions(['setResult']), // Vuex 액션 연결
sendData(value) {
this.setResult(value); // 액션 호출
},
},
};
</script>
[ChildB.vue]
<template>
<div>
<h2>자식 B 컴포넌트</h2>
<p>결과: {{ result }}</p>
</div>
</template>
<script>
import { mapGetters } from 'vuex';
export default {
computed: {
...mapGetters(['getResult']), // Vuex Getter 연결
result() {
return this.getResult; // Vuex의 상태 값 가져오기
},
},
};
</script>
ChildA -> Store
Store -> ChildB
| 특징 | Mitt | Vuex |
|---|---|---|
| 구조 | 이벤트 기반, 느슨한 연결 | 중앙 데이터 관리 구조 |
| 데이터 흐름 | 이벤트 발생 시 실시간 데이터 전달 | 상태를 중앙에서 관리하며 반응형 업데이트 |
| 복잡도 | 간단하고 가볍다 | 상대적으로 설정이 복잡하다 |
| 사용 사례 | 단순한 데이터 전송, 이벤트 처리 | 상태를 공유하고 관리해야 하는 복잡한 앱 |


with 비유
컴포넌트 간 계층적 관계일 때
컴포넌트 간 자유로운 데이터 전달
전체 상태를 중앙에서 관리할 때
| 특징 | Props/Emit | Mitt | Vuex |
|---|---|---|---|
| 구조 | 부모-자식 관계 | 이벤트 버스를 통한 느슨한 연결 | 중앙 상태 관리 구조 |
| 데이터 흐름 | 부모 → 자식 (props), 자식 → 부모 (emit) | 이벤트 발생 시 실시간 데이터 전달 | 상태를 중앙에서 관리하며 반응형 업데이트 |
| 복잡도 | 간단하고 기본적 | 적당히 간단함 | 상대적으로 설정이 복잡함 |
| 사용 사례 | 부모-자식 간 데이터 전송 | 형제 컴포넌트 간 데이터 전송 | 복잡한 앱 상태를 공유하고 관리해야 할 때 |