45
Vue 3 學習之旅
高級特性

Day 45: 透過 ref 存取子元件實例

·6 分鐘閱讀·子元件實例

摘要

模板引用不僅能存取 DOM 元素,也能存取一個子元件的實例,讓我們可以從父元件呼叫子元件內部的方法。

定義與說明

當 ref 屬性被用在一個子元件上時,它引用的將是該子元件的實例。預設情況下,子元件是封閉的,父元件無法存取其內部。子元件必須使用 defineExpose 宏來明確地「暴露」出希望被父元件存取的方法或屬性。

實作範例

子元件實例存取示例
<!-- ChildComponent.vue -->
<script setup>
import { ref } from 'vue';
const message = ref('私有訊息');
function openDialog() { alert('對話框已開啟'); }
// 明確暴露 openDialog 方法
defineExpose({ openDialog });
</script>

<!-- ParentComponent.vue -->
<script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
const childRef = ref(null);
function callChildMethod() {
  // 呼叫子元件暴露出來的方法
  childRef.value.openDialog();
}
</script>
<template>
  <ChildComponent ref="childRef" />
  <button @click="callChildMethod">呼叫子元件方法</button>
</template>

結論

透過 ref 和 defineExpose 的組合,可以實現父元件對子元件的命令式控制。這在某些需要由父層觸發子層特定行為的場景中非常有用。

子元件實例 defineExpose 父子通訊