Published on

Calling a method on child component from parent component in Vue 3 Composition API

Author
  • Name
    A. Fauzi
    Title
    Human Being

I'm just gonna show you how to do it, it's really tricky to do that especially on VueJS because the community is still small and there is no special documentation for that scenario.

First, you have this parent component, I will use Template Refs, you need to add ref property on your child tag

<template> <div> <button @click="clickMe()">Click me!</button> <Child ref="childRef" /> </div> </template> <script> import { defineComponent } from '@nuxtjs/composition-api' import Child from '@/components/Child.vue' export default defineComponent({ components: { Child }, setup () { const childRef = ref(null) const clickMe = () => { childRef.value.callMe() } return { clickMe } } }) </script>

And, in your child component

<template> <div> <div>...</div> </div> </template> <script> import { defineComponent } from '@nuxtjs/composition-api' export default defineComponent({ setup () { const callMe = () => { console.log('thanks for calling me! :)') } return { callMe } } }) </script>

That's it!

Hope this helps, and I hope the Vue community gets bigger, cause Vue is a nice and powerful framework!