跳至主要内容

Day13 - Vue.js 的元件篇:props

備註

本站 Vue 的撰寫風格都是 Composition API

2025 Vue 直播班每日任務,藉由一天學一點積沙成塔

props

  • 父傳子的屬性,父將數據、方法傳給子,子依父狀態進行渲染或動作

Topic

  • 請在 Vue SFC Playground 樣板中使用 props 的方式,將父元件的 titlepricecountimgUrl,這四個屬性的值傳遞到子元件 Card.vue 中,並且能夠正確呈現出畫面。

Result

App.vue
<template>
<div id="app" class="container">
<div class="row">
<template v-for="(fruit, index) in fruitData" :key="index">
<div class="col">
<Card
:title="fruit.title"
:price="fruit.price"
:count="fruit.count"
:imgUrl="fruit.imgUrl"
/>
</div>
</template>
</div>
</div>
</template>
Card.vue
<script setup>
import { defineProps } from 'vue';
const props = defineProps({
title: String,
price: Number,
count: Number,
imgUrl: String,
})
</script>

思考與反饋

  • 學習使用 props 方法,由父傳值給子元件
  1. 先在父元件將值傳給子元件 <Card />
  2. 子元件使用 defineProps 接收父元件傳來的值,並且將值渲染在卡片元件(子)

偷懶版

  • 在跟別人協作時發現有偷懶版寫法,可以直接把整個叫 Card 的物件傳進去
  • 但要注意取值時也要從 props.card.title
    原本的取值就會找不到 <h5 class="card-title">水果名稱:{{ title }}</h5>
App.vue
<template>
<div id="app" class="container">
<div class="row">
<template v-for="(fruit, index) in fruitData" :key="index">
<div class="col">
<Card :card="fruit"/>
</div>
</template>
</div>
</div>
</template>
Card.vue
<script setup>
import { defineProps } from 'vue';
const props = defineProps({
card: {
type: Object,
required: true
}
})
</script>
<template>
<div class="card">
<img :src="props.card.imgUrl" class="card-img-top" :alt="props.card.title">
<div class="card-body">
<h5 class="card-title">水果名稱:{{ props.card.title }}</h5>
<p class="card-text">價錢:{{ props.card.price }}</p>
<p class="card-text">數量:{{ props.card.count }}</p>
<a href="#" class="btn">加入購物車</a>
</div>
</div>
</template>

CODE