'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 way...

Component 2:

export default {
    setup() {
        const continue = (parameter1) => {
            // do stuff here
        }
        
        return {
            continue
        }
    }
}

enter image description here



Solution 1:[1]

One way to solve this is to use events for parent-to-child communication, combined with template refs, from which the child method can be directly called.

  1. In ComponentB.vue, emit an event (e.g., named continue-event) that the parent can listen to. We use a button-click to trigger the event for this example:
<!-- ComponentB.vue -->
<script>
export default {
  emits: ['continue-event'],
}
</script>

<template>
  <h2>Component B</h2>
  <button @click="$emit('continue-event', 'hi')">Trigger continue event</button>
</template>
  1. In the parent, use a template ref on ComponentA.vue to get a reference to it in JavaScript, and create a function (e.g., named myCompContinue) to call the child component's continueFn directly.
<!-- Parent.vue -->
<script>
import { ref } from 'vue'

export default {
  ?
  setup() {
    const myComp = ref()
    const myCompContinue = () => myComp.value.continueFn('hello from B')

    return {
      myComp,
      myCompContinue,
    }
  },
}
</script>

<template>
  <ComponentA ref="myComp" />
  ?
</template>
  1. To link the two components in the parent, use the v-on directive (or @ shorthand) to set myCompContinue as the event handler for ComponentB.vue's continue-event, emitted in step 1:
<template>
  ?
  <ComponentB @continue-event="myCompContinue" />
</template>

demo

Note: Components written with the Options API (as you are using in the question) by default have their methods and props exposed via template refs, but this is not true for components written with <script setup>. In that case, defineExpose would be needed to expose the desired methods.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1