在Vue 3中,父組件向子組件傳遞數據和子組件向父組件通信的方式與Vue 2非常相似,但Vue 3提供了Composition API和更多的響應式API,為組件間的通信提供了更多的可能性。下面是父傳子和子傳父的基本方法:
### 父組件傳遞數據給子組件
在Vue中,父組件通過`props`向子組件傳遞數據。
**父組件**:
```html
<!-- ParentComponent.vue -->
<template>
? <ChildComponent :someProp="parentData" />
</template>
<script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
const parentData = ref('這是來自父組件的數據');
</script>
```
**子組件**:
```html
<!-- ChildComponent.vue -->
<template>
? <div>{{ someProp }}</div>
</template>
<script setup>
import { defineProps } from 'vue';
const props = defineProps({
? someProp: String
});
</script>
```
### 子組件向父組件通信
子組件向父組件通信一般通過自定義事件來實現。子組件使用`emit`觸發事件,父組件監聽這個事件。
**子組件**:
```html
<!-- ChildComponent.vue -->
<template>
? <button @click="notifyParent">點擊我通知父組件</button>
</template>
<script setup>
import { defineEmits } from 'vue';
// 定義emit事件
const emit = defineEmits(['customEvent']);
const notifyParent = () => {
? emit('customEvent', '這是來自子組件的數據');
};
</script>
```
**父組件**:
```html
<!-- ParentComponent.vue -->
<template>
? <ChildComponent @customEvent="handleCustomEvent" />
</template>
<script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
const handleCustomEvent = (data) => {
? console.log(data); // "這是來自子組件的數據"
};
</script>
```
### 總結
- **父傳子**:通過`props`傳遞數據。父組件在使用子組件的標簽時,通過`:屬性名="數據"`的形式傳遞數據給子組件,子組件通過`defineProps`接收數據。
- **子傳父**:通過自定義事件。子組件使用`defineEmits`定義一個事件,然后用`emit`來觸發這個事件并可傳遞數據。父組件在子組件的標簽上使用`@事件名="處理函數"`來監聽這個事件。
Vue 3的Composition API和響應式API為組件間的通信提供了更靈活的方式,但基本原則仍然是利用props和自定義事件實現父子組件間的數據流。