Introduction
Recently, while rewriting a lot of Vue code, I found that there is much knowledge I missed. You may know that Vue components communicate through props down and events up or by using Scoped Slots to pass information.
Another approach is to “explicitly expose certain variables or functions for use by the parent component”.
defineExpose
By default, Vue <script setup>
is closed, and the defineExpose() Compiler Macros inform the compiler about which data to expose to the parent component.
<script setup>const sayHello = () => { console.log('Hello from child!');};
defineExpose({ sayHello});</script>
<template> <Child ref="childRef" /> <button @click="callChildMethod">Call Child Method</button></template>
<script setup>import { ref } from 'vue';import MyChild from './MyChild.vue';
const childRef = ref();
const callChildMethod = () => { childRef.value?.sayHello(); // Call the method exposed by the child component};</script>