What is defineExpose in Vue: Explanation and Usage
defineExpose in Vue is a function used inside the setup() of a component to explicitly expose properties or methods to the parent component. It allows you to control what internal details are accessible when using ref on child components.How It Works
Imagine you have a child component like a black box. Normally, the parent can only interact with what the child chooses to show. defineExpose lets the child decide exactly which parts of itself it wants to share with the parent.
Inside the setup() function of a Vue component, you call defineExpose and pass an object with properties or methods you want to make accessible. This is like giving the parent a special window to peek inside and use those parts.
This is useful because Vue's Composition API hides internal details by default, so defineExpose is the way to share specific things safely without exposing everything.
Example
This example shows a child component exposing a method to the parent using defineExpose. The parent calls the child's method through a ref.
/* ChildComponent.vue */ <script setup> import { ref, defineExpose } from 'vue' const count = ref(0) function increment() { count.value++ } defineExpose({ increment }) </script> <template> <div>Count: {{ count }}</div> </template> /* ParentComponent.vue */ <script setup> import { ref } from 'vue' import ChildComponent from './ChildComponent.vue' const childRef = ref(null) function callIncrement() { childRef.value?.increment() } </script> <template> <ChildComponent ref="childRef" /> <button @click="callIncrement">Increment from Parent</button> </template>
When to Use
Use defineExpose when you want to let a parent component access specific methods or data inside a child component that uses the Composition API. This is common when the parent needs to trigger actions or read values directly from the child.
For example, if you have a custom input component and want the parent to reset it or focus it programmatically, you expose those methods with defineExpose. It keeps your component encapsulated but still flexible.
Key Points
defineExposecontrols what a child component shares with its parent.- It is used inside the
setup()function of Vue components. - Only exposed properties or methods are accessible via
reffrom the parent. - Helps keep component internals private while allowing controlled interaction.
Key Takeaways
defineExpose lets a child component share specific methods or data with its parent.setup() function in Vue's Composition API.ref on the child.