Vue3 Fundamentals · Components, Props & Events

defineExpose

defineExpose

A component written with <script setup> is closed by default. When a parent holds a reference to it, the parent cannot reach the component's internal values or methods.

Sometimes the parent needs one of them — a focus method, a reset, a piece of state. defineExpose decides what the parent is allowed to see:

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

const count = ref(0);

function reset() {
  count.value = 0;
}

defineExpose({ reset });
</script>

The object you pass is the component's public surface. A parent that gets the component through a template ref can call reset, and nothing else is reachable unless you expose it too. Keeping that surface small is the point: you choose what becomes part of the component's contract.

defineExpose is a compiler macro, so you never import it. The Test mounts a parent that holds a ref to your component and checks the ref can reach the exposed method.

Challenge

The parent cannot reach the component's method. Open it deliberately: export an App component from App.vue that defines a reset function and exposes it with defineExpose.

The Test mounts a parent that holds a reference to your component and checks the reference can reach reset. The starter exposes nothing, so the method is unreachable and the Test fails. Add the defineExpose call.

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

const count = ref(0);

function reset() {
  count.value = 0;
}
</script>

<template>
  <p>{{ count }}</p>
</template>

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.