EmilianoJuly 4, 2024

Exposing Child Methods and Properties to a Parent with defineExpose

What is defineExpose()?

defineExpose() is a function used inside a component's setup() to specify which properties and methods should be accessible from the parent component. This is especially useful when a child component needs to expose some of its methods or data so the parent component can interact with them.

Usage example

Child Component (ChildComponent.vue)

<script setup>
import { ref, defineExpose } from "vue";

const count = ref(0);

function increment() {
  count.value++;
}

// Expose the increment method and count property to the parent component
defineExpose({
  increment,
});
</script>

<template>
  <div>
    <button @click="increment">Increase Count</button>
  </div>
</template>

defineExpose({ increment }) is used to expose the increment() method to the parent component. This allows the parent component to call increment() from its own context.

Parent Component

<!-- ParentComponent.vue -->

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

const child = ref(null);

function callIncrement() {
  // Call the increment method from the child component
  child.value.increment();
}
</script>

<template>
  <div>
    <ChildComponent ref="child" />
    <button @click="callIncrement">Call Increment from Parent</button>
  </div>
</template>

The child component is referenced using ref. Then, the increment() method of the child component can be called via child.value.increment().

Benefits of using defineExpose()

  • Encapsulation: Maintains component encapsulation by allowing the child component to expose only what is necessary.
  • Flexibility: Facilitates communication between components, especially when you need a parent component to interact with specific methods of a child component.
  • Code maintainability: Provides a clearer and more structured way to expose properties and methods, improving overall code maintainability.