FE Interview Hub
Vue 3 基礎

父子元件如何溝通?

AI 練習作答

父 → 子:props

父元件透過 props 將資料傳遞給子元件。

<!-- 父元件 Parent.vue -->
<template>
  <Child :message="greeting" :count="num" />
</template>

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

const greeting = ref('Hello!')
const num = ref(42)
</script>
<!-- 子元件 Child.vue -->
<template>
  <p>{{ message }} ({{ count }})</p>
</template>

<script setup>
const props = defineProps({
  message: String,
  count: {
    type: Number,
    required: true,
    default: 0
  }
})
</script>

子 → 父:emit

子元件透過 emit 發出事件,並可攜帶 payload(資料)給父元件。

<!-- 子元件 Child.vue -->
<template>
  <button @click="sendData">送出</button>
</template>

<script setup>
const emit = defineEmits(['update', 'delete'])

function sendData() {
  emit('update', { id: 1, value: 'new value' })
}
</script>
<!-- 父元件 Parent.vue -->
<template>
  <Child @update="handleUpdate" />
</template>

<script setup>
function handleUpdate(payload) {
  console.log('收到子元件的資料:', payload)
}
</script>

父存取子:defineExpose / template ref

<!-- 子元件 Child.vue -->
<script setup>
import { ref } from 'vue'

const count = ref(0)
function reset() { count.value = 0 }

// 必須 expose 才能被父元件存取
defineExpose({ count, reset })
</script>
<!-- 父元件 Parent.vue -->
<template>
  <Child ref="childRef" />
  <button @click="childRef.reset()">Reset</button>
</template>

<script setup>
import { ref } from 'vue'
const childRef = ref(null)
</script>

溝通方式總覽

方向 方法
父 → 子 props
子 → 父 emit
父存取子 ref + defineExpose
雙向綁定 v-model

✦ AI 模擬面試

輸入你的答案,AI 即時分析精準度與改進空間

登入後即可使用 AI 評分