Intermediate LevelVue JS
How does defineExpose() restrict private methods and state when parent components hold template refs?
❓ Interview Prompt: Explain defineExpose() compiler macro, component encapsulation, and exposing explicit public methods to parent template refs.
In '<script setup>', components are closed by default. If a parent component holds a template ref to a child component instance, the parent cannot access any internal refs or methods unless explicitly exposed!
'defineExpose()':
Explicitly declares a public API object that parent components holding a template ref are allowed to access!
Code Implementation Example
html
<!-- CustomInput.vue (Child Component) -->
<script setup>
import { ref } from 'vue';
const inputRef = ref(null);
const internalPrivateData = ref('secret');
const focusInput = () => inputRef.value?.focus();
// EXPOSE ONLY focusInput method to parent; keep internalPrivateData closed!
defineExpose({ focusInput });
</script>
<template>
<input ref="inputRef" type="text" />
</template>💡Exposing explicit public component methods to parents using defineExpose.
🎯 Interview Key Takeaway
Use defineExpose() to control which internal methods and refs are exposed to parents holding template refs.
#defineExpose#Template Refs#Encapsulation#Intermediate
Back to all Vue JS Questions→