父組件調用子組件函式 - daniel-qa/Vue GitHub Wiki

父組件調用子組件函式

如果父組件想要調用子組件中的方法,可以使用 ref 和 defineExpose 的組合來實現。

以下是範例:

範例 1

  • 父組件
<template>
  <div>
    <h1>父組件</h1>
    <button @click="callChildMethod">調用子組件方法</button>
    <Child ref="childRef" />
  </div>
</template>

<script setup>
import { ref } from 'vue';
import Child from './Child.vue';

const childRef = ref(null);

// 呼叫子組件方法
const callChildMethod = () => {
  if (childRef.value) {
    childRef.value.childMethod();
  }
};
</script>
  • 子組件
<template>
  <div>
    <h2>子組件</h2>
    <p>這是子組件。</p>
  </div>
</template>

<script setup>
import { defineExpose } from 'vue';

// 定義子組件方法
const childMethod = () => {
  console.log('子組件方法被調用!');
};

// 將方法暴露給父組件
defineExpose({
  childMethod,
});
</script>
  • 解釋

defineExpose:在子組件中使用 defineExpose 來暴露方法,讓父組件能夠通過 ref 訪問子組件中的方法。

ref:在父組件中,使用 ref 綁定子組件,這樣可以通過 childRef.value 訪問到子組件的實例。

調用方法:在父組件中,可以通過 childRef.value.childMethod() 來調用子組件的 childMethod 方法。

這樣,父組件就能夠調用子組件中的方法了!

範例 2 (有參數)

  • 父組件
<template>
  <div>
    <h1>父組件</h1>
    <button @click="callChildMethodWithRef">調用子組件方法並傳遞 ref</button>
    <Child :titleRef="titleRef" :subjectRef="subjectRef" ref="childRef" />
    <p>父組件中的標題: {{ titleRef }}</p>
    <p>父組件中的主題: {{ subjectRef }}</p>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import Child from './Child.vue';

const titleRef = ref('Hello World');
const subjectRef = ref('Vue 3');

const childRef = ref(null);

// 呼叫子組件方法並傳遞 ref
const callChildMethodWithRef = () => {
  if (childRef.value) {
    childRef.value.childMethod(titleRef, subjectRef);
  }
};
</script>
  • 子組件
<template>
  <div>
    <h2>子組件</h2>
    <p>接收到的標題: {{ titleRef }}</p>
    <p>接收到的主題: {{ subjectRef }}</p>
  </div>
</template>

<script setup>
import { defineProps, defineExpose } from 'vue';

const props = defineProps({
  titleRef: {
    type: Object,
    required: true,
  },
  subjectRef: {
    type: Object,
    required: true,
  },
});

// 定義子組件方法,操作傳入的 ref
const childMethod = (titleRef, subjectRef) => {
  console.log('子組件方法被調用!');
  console.log('接收到的 titleRef:', titleRef.value);
  console.log('接收到的 subjectRef:', subjectRef.value);
  
  // 修改傳入的 ref
  titleRef.value = 'Updated Title from Child';  
  subjectRef.value = 'Updated Subject from Child';
};

// 將方法暴露給父組件
defineExpose({
  childMethod,
});
</script>
⚠️ **GitHub.com Fallback** ⚠️