What is Vue defineExpose?

Vue defineExpose 是啥?子元件如何溝通?

前言

近期要重寫很多的 Vue 發現多得是我需要多補充的知識。你可能了解 Vue 元件間透過 props🔗 down 與 event🔗 up 或是使用 Scoped Slots🔗 來傳遞資訊。

還有一種做法是「顯式地暴露某些變數或函式給父組件使用」。

defineExpose

預設 Vue <script setup> 是封閉的,透過 defineExpose()🔗 Compiler Macros (宏編譯器)寫給編譯器告知要曝露哪些資料給父元件。

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(); // 呼叫子元件暴露的方法
};
</script>

延伸閱讀