LESSON-21 · TOPIC 01

prop type、default、required

能為 service-card 宣告必要 title 與具預設值的 price,並從元件設定與渲染結果驗證輸入契約。

code-edit元件輸入、事件與 slot 契約|prop type、default、required本頁只練一個責任

本頁只練什麼

能為 service-card 宣告必要 title 與具預設值的 price,並從元件設定與渲染結果驗證輸入契約。

未宣告輸入契約時,拼錯名稱、漏傳必要資料或型別錯誤只會在畫面深處變成模糊結果。

要修改的檔案:files/starter/main.js

定位:先讀元件 props object,不先從最終文字猜契約。|依 starter-1 定位,只修改「prop type、default、required」的責任。

任務情境

先結果,再原理;完成後要能說出自己看見的證據。

現在的問題

部分卡片漏傳 price 後顯示空白,團隊不知道這是允許狀態還是資料錯誤。

起始狀態:兩個元件實例尚未解析輸入與預設值。

完成後要看到

requiredDeclared=true、typeDeclared=true、explicitPrice=1200、defaultPrice=洽詢。

驗收證據:requiredDeclared/typeDeclared=true、explicitPrice=1200、defaultPrice=洽詢

何時會用到

元件由外部資料驅動,且需要可讀、可驗證的輸入介面時。

常見混淆:default 只在 prop resolved value 為 undefined 時套用,不會把 null 自動改成預設。

觀念與最小範例

這段程式是理解起點,不是要你直接跳過 Starter。

prop type、default、required Prop type, default, and required declarations

元件要先寫收件規則:哪一項必填、要什麼型別、沒填時用什麼預設。

正式說法:Props declaration 定義 parent-to-child public input schema;object syntax 可設定 type、required 與 default。

props:{title:{type:String,required:true},price:{type:[Number,String],default:'洽詢'}}。

三步完成本主題

每一步都留下可觀察結果;如果沒看到,先看「卡住先查」。

  1. Step 1|先看見目前缺口,不急著貼答案。

    檔案:files/starter/main.js 定位:先讀元件 props object,不先從最終文字猜契約。

    要做:先重新載入 Starter,記錄目前畫面、DOM、Computed、Console 或文件內容。

    預期:能指出「先讀元件 props object,不先從最終文字猜契約。」目前的缺口。

    證據:保存 files/starter/main.js 的目前狀態,並指出下一步只會修改哪個檔案責任。

    卡住先查:確認開啟的是 files/starter/main.js,且定位到 先讀元件 props object,不先從最終文字猜契約。。

  2. Step 2|只修改本主題的一個責任。

    檔案:files/starter/main.js 定位:先讀元件 props object,不先從最終文字猜契約。

    要做:掛載兩個不同輸入的卡片,核對必要/型別宣告與 explicit/default 顯示。

    預期:requiredDeclared=true、typeDeclared=true、explicitPrice=1200、defaultPrice=洽詢。

    證據:requiredDeclared/typeDeclared=true、explicitPrice=1200、defaultPrice=洽詢

    卡住先查:先讀元件 props object,不先從最終文字猜契約。

  3. Step 3|重新載入並以證據驗收,不以『看起來差不多』判定完成。

    檔案:files/starter/main.js 定位:先讀元件 props object,不先從最終文字猜契約。

    要做:重新整理頁面,再逐項比對預期結果與 evidence。

    預期:requiredDeclared=true、typeDeclared=true、explicitPrice=1200、defaultPrice=洽詢。

    證據:requiredDeclared/typeDeclared=true、explicitPrice=1200、defaultPrice=洽詢

    卡住先查:先讀元件 props object,不先從最終文字猜契約。

觀察示範

這個示範只讓你看懂概念,不會替你修改 Starter,也不會自動宣告完成。

prop type、default、requiredruntime fixture · read-only demo
本主題示範畫面:

驗收證據

勾選只是學習紀錄;真正完成仍要回到 Starter 的實際結果。

提示 1|方向

必要 title 與可省略 price 的責任不同。

提示 2|關鍵片段

title 設 String/required;price 設 [Number,String]/default。

提示 3|完整解答與原因

完整解答與原因:title 宣告 String 且 required;price 接收 Number/String 並 default='洽詢',兩個實例分別證明明確值與預設值。

完成後進入下一階段,或回到入口選下一個 topic。

開始 Starter →回到主題清單