WeHelp
Vue 是一款用於建構使用者介面的 JavaScript 前端框架,提供高效的資料綁定與組件化開發能力。
  1. Vue 框架簡介
  2. Vite 專案管理
  3. 第一個 Vue 專案
  4. Vue 專案結構
  5. 樣板語法,內文與屬性
  6. 樣板語法,流程控制
  7. 樣板語法,事件處理
  8. Vue 響應式狀態
  9. 表單與響應式狀態
  10. 組件開發:基本觀念
  11. 組件開發:傳遞屬性
  12. 組件開發:自訂事件
  13. 組件的生命週期
  14. 串接後端資料
組件開發:傳遞屬性
## 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 網站前端工程
從 0 開始,成為網站前端工程師的學習路徑。