How to call a child method from a parent component in Vue 3 with <script setup>

dinsdag 12 december 2023 - 188 woorden, 1 min read

Short explanation how to call a function in a child component from the parent component in Vue3.

With defineExpose() within your component you will expose the functions (or other component properties) to the parent components. In this simple example I used an HTML dialog element with the native .showModal() and .close() methods wrapped in a show and close function.

childComponent.vue:

<script setup>
  // The Dialog element in a Vue ref.
  const dialog = ref(document.getElementById('dialog'))

  // This function can be called from the parent component.
  const show = () => {
    dialog.value.showModal()
  }

  // This function can be called from the parent component.
  const close = () => {
    dialog.value.close()
  }
  
  // We expose the function which can be called from the parent component.
  defineExpose({
    show,
    close
  })
</script>
<template>
  <dialog ref="dialog">
    <form method="dialog">
      <button @click="close">Close</button>
      <button type="submit">Submit</button>
    </form>
  </dialog>  
</template>

parentComponent.vue:

<script setup>
  // Attach the component to a Vue ref.
  const modalRef = ref()
  
  const openModal = () => {
    // Through the ref we can call the show function within the childComponent.
    modalRef.show()
  }
</script>
<template>
  <button @click="openModal">Open modal</button>
  <childComponent ref="modalRef"></childComponent>
</template>

Looking for the opposite?
How to call a parent method from a child component.

Resources


Sebastian Hagens @Sebastix
I work as creative webdeveloper & tech consultant and care about digital freedoms. Follow me:
or visit my contact page