#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
3 min read
Question 37 of 37easy

What is defineExpose in Vue?

Exposing component methods to parent.

What You'll Learn

  • Why defineExpose is needed
  • What to expose
  • Usage with refs

The Problem

With script setup, component internals are closed by default:

code.txtVUE
<!-- Child.vue -->
<script setup>
const count = ref(0)
function reset() { count.value = 0 }
</script>

<!-- Parent.vue -->
<script setup>
const childRef = ref()
childRef.value.reset() // Error! reset is not exposed
</script>

Using defineExpose

code.txtVUE
<!-- Child.vue -->
<script setup>
const count = ref(0)
function reset() { count.value = 0 }
function increment() { count.value++ }

// Explicitly expose to parent
defineExpose({
  reset,
  count
})
</script>

<!-- Parent.vue -->
<script setup>
const childRef = ref()

function resetChild() {
  childRef.value.reset() // Works!
  console.log(childRef.value.count) // Works!
}
</script>

<template>
  <Child ref="childRef" />
</template>

TypeScript

code.tsTypeScript
// Child exposes
defineExpose({
  reset: () => void
})

// Parent types the ref
const childRef = ref<InstanceType<typeof Child> | null>(null)