在 Vue 3 中,父組件點擊按鈕觸發子組件事件有以下三種常用方式:
方法 1:使用?ref
?直接調用子組件方法(推薦)
vue
復制
下載
<!-- 父組件 --> <template><button @click="callChildMethod">父組件按鈕</button><ChildComponent ref="childRef" /> </template><script setup> import { ref } from 'vue'; import ChildComponent from './ChildComponent.vue';const childRef = ref(null);function callChildMethod() {if (childRef.value) {childRef.value.childMethod(); // 直接調用子組件方法} } </script>
vue
復制
下載
<!-- 子組件 ChildComponent.vue --> <script setup> // 暴露給父組件的方法 const childMethod = () => {console.log('子組件方法被調用');// 執行子組件邏輯 };// 暴露方法給父組件 defineExpose({childMethod }); </script>
方法 2:通過 Props 傳遞回調函數
vue
復制
下載
<!-- 父組件 --> <template><button @click="triggerChild">父組件按鈕</button><ChildComponent :parentCallback="callback" /> </template><script setup> import ChildComponent from './ChildComponent.vue';const callback = () => {console.log('父組件的回調函數被執行'); };function triggerChild() {// 通過觸發子組件事件間接執行// 實際執行邏輯在子組件內 } </script>
vue
復制
下載
<!-- 子組件 --> <template><!-- 接收父組件傳遞的回調 --> </template><script setup> const props = defineProps(['parentCallback']);// 子組件內執行回調 function executeParentCallback() {if (props.parentCallback) {props.parentCallback();} }// 暴露方法供父組件調用 defineExpose({ executeParentCallback }); </script>
方法 3:使用自定義事件(子組件觸發)
vue
復制
下載
<!-- 父組件 --> <template><button @click="emitEvent">父組件按鈕</button><ChildComponent @child-event="handleEvent" /> </template><script setup> import ChildComponent from './ChildComponent.vue';function emitEvent() {// 觸發自定義事件(實際由子組件監聽) }function handleEvent(data) {console.log('收到子組件事件:', data); } </script>
vue
復制
下載
<!-- 子組件 --> <script setup> const emit = defineEmits(['child-event']);// 當需要執行時觸發事件 function triggerEvent() {emit('child-event', { data: '子組件數據' }); }defineExpose({ triggerEvent }); </script>
推薦方案對比
方法 | 優點 | 適用場景 |
---|---|---|
ref ?直接調用 | 直接高效,邏輯清晰 | 父組件直接控制子組件特定操作 |
Props 回調函數 | 符合單向數據流 | 需要傳遞數據到父組件的情況 |
自定義事件 | 符合組件解耦原則 | 子組件主動通知父組件的場景 |
最佳實踐建議:
-
需要直接控制子組件行為時 → 使用?
ref
?方法 -
需要子組件返回數據時 → 使用 Props 回調
-
實現組件解耦時 → 使用自定義事件
根據你的具體場景選擇最合適的方式,通常?ref
?直調是最直接高效的解決方案。