728x90

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>
728x90

+ Recent posts