Calling method on Child Component - Composition API

Viewed 6311

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

2 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>

You're missing the value field in your ref, it should be :

 const callChildMethod = () = {
  child.value.doSomething()
}

Edit amazing-cori-5hgi9

If the child component is defined using the script setup syntax you should use defineExpose to expose the method to the outside

<script setup>

function doSomething(){
  //......
}

defineExpose({
  doSomething,
});

</script>

Parent :

<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
    }
  }
</scrip>

or

<template>
  <div>
    <button @click="callChildMethod">
    <child-component ref="child" />
  </div>
</template>
<script script>

    const child = ref(null)
    const callChildMethod = () => {
      child.doSomething()
    }


</scrip>
Related