Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling method on Child Component - Composition API

I have a parent component where I need to call a method that exists in one of its child components:

<template>
  <div>
    <button @click="callChildMethod">
    <child-component ref="child" />
  </div>
</template>
<script>
  setup(props) {
    const child = ref(null)
    const callChildMethod = () => {
      child.doSomething()
    }

    return {
      child,
      callChildMethod
    }
  }
</script>
  

The child component contains the doSomething method:

const doSomething = () => { console.log('calling method....') }

Since I'm using the VueJS3 and the Composition API, my approach was to use a template ref to call the method in the child component. Obviously is not working but I can't see what I'm missing. Does someone have a clue about this one? Thanks in advance

like image 585
Deric Lima Avatar asked Sep 09 '25 15:09

Deric Lima


1 Answers

P.s. for <script setup> (Composition API) need to use defineExpose

https://v3.vuejs.org/api/sfc-script-setup.html#defineexpose

Parent component:

<script setup>
...
const childred = ref();

childred.value.doSomething()
</script>

<template>
  <ChildrenComponent ref="childred" />
</template>

ChildrenComponent:

<script setup>
...
function doSomething(){
  console.log(1);
}

defineExpose({
  doSomething,
});

</script>

<template>
  <div>123</div>
</template>

like image 199
Андрей Сорока Avatar answered Sep 12 '25 04:09

Андрей Сорока