Blog>
Snippets

Interacting with Child Component Methods

Show how to call methods of a child component from a parent component using template refs in Vue.js 3.
// ParentComponent.vue
<template>
  <ChildComponent ref="childComponentRef" />
  <button @click="callChildMethod">Call Child Method</button>
</template>

<script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';

const childComponentRef = ref(null);

function callChildMethod() {
  if (childComponentRef.value) {
    childComponentRef.value.someMethod();
  }
}
</script>
In the parent component, we define a template ref `childComponentRef` on the ChildComponent instance. Upon clicking the button, the `callChildMethod` function is triggered, which then calls `someMethod` on the child component using the template ref.
// ChildComponent.vue
<template>
  <!-- Child component's template -->
</template>

<script setup>
import { defineExpose } from 'vue';

function someMethod() {
  // Logic for the method that can be called by the parent
  console.log('Child method called!');
}

// Expose the method so it can be called by parent
defineExpose({
  someMethod
});
</script>
In the child component, we define a method `someMethod` that will be callable by the parent. We use `defineExpose` to make it accessible to the parent through the template ref.