DEV Community

Ankit Verma
Ankit Verma

Posted on

What is defineExpose in Vue.js? (With Simple Example)

It’s used to share things (like functions or data) from a child component to its parent — but only if you want to.

Let’s see what it is, why you need it, and how to use it.


💡 Why Use defineExpose?

When you use the <script setup> style in Vue 3, everything inside is private by default. That means a parent component can’t access anything inside a child component — unless you expose it.

That’s where defineExpose() comes in.


🧪 Example: Expose a Method to the Parent

👶 ChildComponent.vue

<template> <button @click="increment">Clicked {{ count }} times</button> </template> <script setup> import { ref } from 'vue' const count = ref(0) function increment() { count.value++ } function reset() { count.value = 0 } // 👇 Make reset() available to the parent defineExpose({ reset }) </script> 
Enter fullscreen mode Exit fullscreen mode

👨‍👩‍👧 ParentComponent.vue

<template> <ChildComponent ref="childRef" /> <button @click="resetChild">Reset from Parent</button> </template> <script setup> import { ref } from 'vue' import ChildComponent from './ChildComponent.vue' const childRef = ref(null) function resetChild() { childRef.value.reset() // Call child’s reset() method } </script> 
Enter fullscreen mode Exit fullscreen mode

✅ When to Use It

Use defineExpose if:

  • You want the parent to call a method in the child (like reset, submit, etc.)
  • You want to get data from the child component

⚠️ Notes

  • Only works inside <script setup>
  • Only needed if parent uses ref to access the child
  • Keeps your code clean and controlled by exposing only what’s needed

Top comments (0)