프로그래밍/Js

vue3 composition api 에서 다른 컴포넌트 함수 호출

소행성왕자 2023. 6. 13. 11:48

composition api 의 <script setup> 을 이용하여 다른 컴포넌트의 값을 가져오거나 

다른 컴포넌트 함수를 호출하는 방법을 알아보도록 한다.

App.vue

<script setup>

const dd = (log, head='') => {
    console.log('>>>'+head);
    console.log(log)
};


import {
  ref,
  onMounted,
  onUnmounted,
  watch,
  reactive,
  defineExpose,
  defineProps,
} from 'vue';


import send from '@/components/send.vue'

const child = ref(null);
const onCall = () => {
  dd(child.value.a, 'child.value.a')
  child.value.tt();
};

onMounted(()=>{
  Worker.init();
  onCall();  
})

</script>


<template>
    <div>
        <send ref="child"/>
    </div>
</template>

send.vue (자식 컴포넌트)

<script setup>
import { W1910A01 } from '@/store/W1910A01';

const a = '123';
const tt =_=>alert(123);

defineExpose({
    tt,a
});

</script>  

<template>
</template>

주의) defineExpose 없으면 작동하지 않습니다.

 

 

참고 : https://stackoverflow.com/questions/72223441/call-a-function-from-another-component-using-composition-api

 

Call a function from another component using composition API

Below is a code for a header and a body (different components). How do you call the continue function of the component 2 and pass a parameter when you are inside component 1, using composition API ...

stackoverflow.com

https://stackoverflow.com/questions/73344760/defineexpose-from-components-script-setup-not-working-in-vue-3

 

defineExpose from component's <script setup> not working in vue 3

New to Vue in general and currently using 3.2.37, I possibly missunderstood the correct usage of composition api’s defineExpose directive as documented here: https://vuejs.org/api/sfc-script-setup....

stackoverflow.com