What is Vue defineExpose?

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.

Child.vue
<script setup>
const sayHello = () => {
console.log('Hello from child!');
};
defineExpose({
sayHello
});
</script>
parent.vue
<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>

Further Reading