今天將延續昨天的內容,繼續介紹父元件向子元件傳遞資料的方式 Props
當從外部傳入的 props 不符合資料類型的要求, Vue 會在瀏覽器的控制台顯示錯誤訊息來提醒開發者,在團隊開發中是個很實用的功能,其中 Vue 內建能夠檢查的 type 屬性有 String 、 Number 、 Boolean 、 Array 、 Object 、 Date 、 Function 、 Symbol 。
1.指定單一資料類型
以下程式碼將指定傳入的 title 為 String 的資料類型。
props: {
title: {
type: String //寫入指定的資料型別,注意首字需要大寫
}
}
2.指定多種資料類型
透過使用陣列的方式來指定多種不同的資料型別。
props: {
data: {
type: [String, Number] //允許 String 和 Number 的資料類型傳入
}
}
3.指定必要屬性
透過加上 required 屬性並設定為 true ,指定此 props 為必要的屬性。
props: {
name: {
type: String,
required: true
}
}
4.指定預設值
透過加上 default 屬性來指定 props 的預設內容。
props: {
message: {
type: String,
default: 'Hello World!'
}
}
5.自定義驗證
使用 validator 函數來自定義驗證規則,也就是可以自己寫入邏輯來驗證 props 的值,當驗證失敗時,Vue 會在控制台顯示錯誤訊息。
props: {
score: {
type: Number,
validator(value) {
return value >= 0 && value <= 100 //定義數字範圍為0到100
}
}
}
https://book.vue.tw/CH2/2-2-communications.html
https://zh-hk.vuejs.org/guide/components/props.html
https://hackmd.io/@CynthiaChuang/Vue-Study-Notes-Contents/%2F%40CynthiaChuang%2FVue-Study-Notes-Unit06%23props-%25E4%25BD%25BF%25E7%2594%25A8%25E4%25B8%258A%25E7%259A%2584%25E6%25B3%25A8%25E6%2584%258F%25E4%25BA%258B%25E9%25A0%2585