Skip to content

Vue 3 實戰:掌握 Props 傳值技巧與 Data Validation 型別驗證

在 Vue 的元件化架構中,Props 是父元件向子元件傳遞資料的唯一官方管道。透過明確宣告 Props,Vue 才能精準區分哪些屬性是「資料輸入」,哪些是單純的「屬性穿透(Fallthrough Attributes)」。

如何宣告 Props:使用 defineProps

<script setup> 中,我們使用內建函式 defineProps 來宣告元件接收的資料。

基礎陣列宣告

這是最簡單的方式,適合開發初期快速原型製作:

js
// defineProps(["name", "age"]);
const props = defineProps(["name", "age"]);

console.log(props.name);
console.log(props.age);

物件宣告與型別檢查

為了大型專案的維護性,建議使用 物件形式。這不僅能規範資料型別,當傳入錯誤型別時,Vue 還會在瀏覽器控制台發出警告,幫助您提早發現錯誤。

js
defineProps({
  name: {
    type: String,
    default: "",
  },
  age: {
    type: Nubmer,
    default: 10,
  },
});

靜態與動態 Props 的應用場景

在 Template 綁定 Props 時,需注意 靜態動態 的差異:

  • 靜態:值是固定字串,不會隨資料變動。

    html
    <!-- 傳入的是字串 "iPhone 17 Pro Max" -->
    <ProductCard title="iPhone 17 Pro Max" />
  • 動態:綁定變數、表達式、運算結果。

    html
    <!-- 傳入的是變數 currentPrice 的值 -->
    <ProductCard :price="currentPrice" />

重要規範:單向數據流 (One-Way Data Flow)

所有的 props 都遵循 單向數據 流的原則:

  • 數據向下流動:父層狀態更新時,Props 會自動同步給子元件。
  • 禁止逆向修改:子元件不應在內部直接修改 Props。這樣可以確保數據流向清晰,避免多個子元件同時修改父層狀態導致維護災難。

實戰提醒

如果您試圖在子元件內修改 Prop 值,Vue 會在主控台(Console)噴出警告。若需要修改該資料,請考慮使用 emit 通知父層更新,或將其作為 ref 的初始值轉化為元件內部狀態。

實戰範例

靜態傳遞

動態傳遞

js
["html", "rwd", "javascript", "vue", "sass"];
css
.box__ls {
  padding-left: 0;
  list-style-type: none;
}

.bevel__item {
  position: relative;
  padding: 1rem;
  color: #666;
  line-height: 1;
  list-style-type: none;
  text-transform: uppercase;
  border: solid 1px #ccc;
}

.bevel__item::before,
.bevel__item::after {
  position: absolute;
  width: 16px;
  height: 16px;
  background-color: #fff;
  content: "";
  transform: rotate(45deg);
}

.bevel__item::before {
  top: -9px;
  left: -9px;
  border-right: solid 1px #ccc;
}

.bevel__item::after {
  bottom: -9px;
  right: -9px;
  border-left: solid 1px #ccc;
}

.bevel__item + .bevel__item {
  margin-top: 1rem;
}

型別與驗證

js
{
  name: 'Away',
  fullName: () => `${user.name} Hung`,
  age: 41,
  isMale: true,
  skills: ['RWD', 'CSS', 'Javascript', 'HTML'],
  books: {
    name1: 'ACA 國際認證教戰手冊:Dreamweaver CS5 完全攻略',
    name2: 'Illustrator CS5(補習班內部用書)',
    name3: 'Illustrator CS4(補習班內部用書)',
  },
}

動態傳遞與狀態控管

js
[
  {
    id: 1,
    isRelease: false,
    name: "梵蒂岡驅魔士",
  },
  {
    id: 2,
    isRelease: true,
    name: "超級瑪利歐兄弟電影版",
  },
  {
    id: 3,
    isRelease: true,
    name: "捍衛任務4",
  },
  {
    id: 4,
    isRelease: false,
    name: "星際異攻隊3",
  },
  {
    id: 5,
    isRelease: true,
    name: "鈴芽之旅",
  },
];
css
/* 基本樣式 */
.box {
  padding: 0.7rem 1rem;
  margin-bottom: 1rem;
}

/* 已上映 */
.box--release {
  background-color: lightblue;
}

/* 未上映 */
.box--no-release {
  color: #ccc;
  background-color: #eee;
}