組件開發:傳遞屬性
## Vue 父組件傳遞資料給子組件
在 Vue 中,父組件可以透過 **Props** 將資料傳給子組件。
資料流向如下:
```text
父組件 ── props ──> 子組件
```
基本概念:
1. 父組件在使用子組件時,透過屬性傳值。
2. 子組件使用 `defineProps()` 接收資料。
3. Props 是「單向資料流」,子組件不應直接修改父組件傳入的資料。
4. 如果子組件需要通知父組件更新資料,通常會使用 `emit`。
---
## 範例:使用者資訊卡
此範例由兩個組件組成:
- `App.vue`:父組件
- `UserCard.vue`:子組件
父組件會將使用者資料與標題傳給子組件。
### `src/App.vue`
```vue
<script setup>
import UserCard from './components/UserCard.vue'
const user = {
name: '王小明',
email: 'ming@example.com',
role: '前端工程師'
}
</script>
<template>
<main class="page">
<h1>使用者頁面</h1>
<!-- 將 title 與 user 傳給子組件 -->
<UserCard
title="使用者資訊"
:user="user"
/>
</main>
</template>
<style scoped>
.page {
max-width: 600px;
margin: 40px auto;
font-family: Arial, sans-serif;
}
</style>
```
### `src/components/UserCard.vue`
```vue
<script setup>
const props = defineProps({
title: {
type: String,
required: true
},
user: {
type: Object,
required: true
}
})
</script>
<template>
<section class="card">
<h2>{{ props.title }}</h2>
<p>
<strong>姓名:</strong>
{{ props.user.name }}
</p>
<p>
<strong>Email:</strong>
{{ props.user.email }}
</p>
<p>
<strong>職位:</strong>
{{ props.user.role }}
</p>
</section>
</template>
<style scoped>
.card {
padding: 24px;
border: 1px solid #ddd;
border-radius: 10px;
background-color: #f9f9f9;
box-shadow: 0 2px 8px rgb(0 0 0 / 10%);
}
.card h2 {
margin-top: 0;
color: #42b883;
}
</style>
```
## 傳值方式說明
```vue
<UserCard
title="使用者資訊"
:user="user"
/>
```
其中:
```vue
title="使用者資訊"
```
是傳入字串,子組件會收到:
```js
title: '使用者資訊'
```
而:
```vue
:user="user"
```
前面的 `:` 代表動態綁定,會將父組件中的 JavaScript 變數 `user` 傳入子組件,而不是單純傳入字串 `"user"`。
子組件則透過:
```js
const props = defineProps({
title: String,
user: Object
})
```
接收資料,並在模板中使用:
```vue
{{ props.user.name }}
```
也可以使用解構方式簡化:
```vue
<script setup>
const { title, user } = defineProps({
title: String,
user: Object
})
</script>
<template>
<h2>{{ title }}</h2>
<p>{{ user.name }}</p>
</template>
```
重點是:**父組件負責提供資料,子組件負責顯示或使用資料。**
相關學習地圖、教學課程
F2E 網站前端工程