Vue 3에서 postMessage 이벤트를 이용한 자식 컴포넌트와 부모 컴포넌트 간 통신
Vue 3에서 자식 컴포넌트와 부모 컴포넌트 간 통신 방법에는 다양한 방식이 존재하지만, postMessage 이벤트를 활용하는 방법은 비교적 간단하고 유연한 장점을 제공합니다.
1. postMessage 이벤트란 무엇인가요?
postMessage 이벤트는 웹 브라우저에서 서로 다른 창이나 웹 페이지 간에 메시지를 전달하는 데 사용되는 API입니다. 자식 컴포넌트와 부모 컴포넌트가 서로 다른 DOM 트리에 위치하는 경우, postMessage 이벤트를 통해 안전하고 효율적으로 통신할 수 있습니다.
2. postMessage 이벤트를 활용한 자식-부모 컴포넌트 통신 예시:
부모 컴포넌트 (ParentComponent.vue):
<template>
<div>
<button @click="openChildComponent('child-component', 800, 700)">자식 컴포넌트 새 창으로 띄우기</button>
</div>
</template>
<script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
const isChildComponentOpen = ref(false);
const openChildComponent = () => {
const left = screen.width ? (screen.width - width) / 2 : 0
const top = screen.height ? (screen.height - height) / 2 : 0
const attr = `top=${top}, left=${left}, width=${width}, height=${height}, resizable=no,status=no`
const childWindow = window.open(url, '_blank', attr)
childWindow.postMessage({ data: { parent: this } }, '*')
childWindow.addEventListener('message', (event) => {
if (event.data.type === 'closeChildComponent') {
isChildComponentOpen.value = false;
childWindow.close();
}
});
isChildComponentOpen.value = true;
};
</script>
자식 컴포넌트 (ChildComponent.vue):
<template>
<div>
<button @click="closeWindow">창 닫기</button>
</div>
</template>
<script setup>
const closeWindow = () => {
parent.postMessage({ type: 'closeChildComponent' }, '*');
};
</script>
3. postMessage 이벤트 활용의 장점:
- 유연성: 서로 다른 DOM 트리에 위치하는 컴포넌트 간 통신에 효과적입니다.
- 보안: window.postMessage API는 메시지 전달에 있어 기본적인 보안 기능을 제공합니다.
- 사용 편의성: 비교적 간단하고 직관적인 방식으로 구현 가능합니다.
4. postMessage 이벤트 활용 시 주의점:
- 메시지 직렬화: postMessage은 메시지를 문자열 형태로 전달하기 때문에, 객체나 배열과 같은 복잡한 데이터를 전달할 때는 직렬화/역직렬화 과정이 필요합니다.
- 보안 고려: postMessage을 사용할 때는 출처를 확인하고 악意적인 메시지에 대한 대비책을 마련하는 것이 중요합니다.
- 다른 방법 고려: 상황에 따라 props, provide/inject, Vuex와 같은 다른 통신 방법이 더 적합할 수 있습니다.
728x90
'웹개발 > vuejs' 카테고리의 다른 글
[Vue] Vue3 defineExpose 사용 가이드 (0) | 2024.07.20 |
---|---|
Vue 3 및 Router 4 기초부터 상세 가이드 (4) | 2024.07.20 |
[Vue] TypeError: Intl.RelativeTimeFormat is not a constructor 에러 해결 방법 (0) | 2024.07.19 |
[Vue] Vue3에서 setup() 함수와 함께 Axios와 Async/Await 사용하기 (1) | 2024.07.16 |
[Vue] Vue2에서 Axios와 함께 Async/Await 사용하기 (0) | 2024.07.16 |