vue3 에서 컴포넌트간에 메서드 호출 예시를 예제로 알아 본다. 작업을 하다 보면 자식 컴포넌트에서 부모 컴포넌트의 메소드를 호출하기도 하고 반대로 부모 컴포넌트에서 자식 컴포넌트 함수를 호출 하기도 한다.
아래 예시는 <script setup> 코드로 vue3 이다. 자식 컴포넌트에서 부모를 호출하는 부분은 defineExpose 에 정의해 주어야 하고 부모컴포넌트에서 받아 오는 값은 props 로 정의해주어야 한다.
<template>
<div>
<p>받은 값: {{ receivedValue }}</p>
<button @click="callParentFunction">부모 함수 호출</button>
</div>
</template>
<script setup>
import { defineProps, defineExpose } from 'vue';
// 부모로부터 값을 받기
const props = defineProps({
receivedValue: String,
});
// 자식에서 부모가 호출할 수 있는 함수를 정의
const childFunction = () => {
console.log('자식 함수가 호출되었습니다!');
};
// 부모가 호출할 수 있도록 expose
defineExpose({
childFunction,
});
</script>
부모컴포넌트에서 자식함수를 호출 하려면 ref 를 정의하고 호출 할수 있다.
<template>
<div>
<h1>부모 컴포넌트</h1>
<ChildComponent ref="childRef" :receivedValue="parentValue" @childEvent="handleChildEvent" />
<button @click="callChildFunction">자식 함수 호출</button>
</div>
</template>
<script setup>
import ChildComponent from './ChildComponent.vue';
import { ref } from 'vue';
// 부모 컴포넌트의 상태
const parentValue = ref('부모에서 전달한 값');
// 자식의 이벤트를 처리하는 메서드
const handleChildEvent = (message) => {
console.log(message); // "자식에서 호출된 이벤트" 출력
};
// 자식 컴포넌트에 대한 참조 생성
const childRef = ref(null);
// 자식의 함수를 호출하는 메서드
const callChildFunction = () => {
if (childRef.value) {
childRef.value.childFunction(); // 자식의 함수를 호출
}
};
</script>
'VUE' 카테고리의 다른 글
vue store 변수 저장 (0) | 2024.12.02 |
---|---|
vue3 약관동의 체크박스 구현 예시 (0) | 2024.11.22 |
vue3 새창으로 링크 걸기 (0) | 2024.11.16 |
vue api 호출 에러 처리 interceptor.js 파일 예제 (0) | 2024.11.14 |
vue3 inputbox 에서 enter 키로 다음 inputbox 이동 되는 스크립트 (0) | 2024.07.25 |