javascript / intermediate
Snippet
Controlled Child Components via defineExpose
In Vue 3's <script setup>, components are 'closed' by default, meaning their internal properties are not accessible to parent components via template refs. The defineExpose macro allows you to explicitly choose which internal methods or state should be public.
snippet.js
1
2
3
4
5
6
7
8
// Inside Child.vueimport { ref } from 'vue';const internalCount = ref(0);const reset = () => (internalCount.value = 0);defineExpose({reset});
vue
Breakdown
1
const internalCount = ref(0);
A private reactive variable that remains hidden unless explicitly exposed.
2
defineExpose({ ... });
A compiler macro that defines the public interface of the component instance.
3
reset
The specific function that the parent can now call using a component reference.