iT邦幫忙

2025 iThome 鐵人賽

DAY 16
0
Vue.js

新手學習Vue.js與實作之旅系列 第 16

Day16 Vue 元件間的傳遞 Props (下)

  • 分享至 

  • xImage
  •  

今天將延續昨天的內容,繼續介紹父元件向子元件傳遞資料的方式 Props /images/emoticon/emoticon07.gif

Props 資料類型的驗證

當從外部傳入的 props 不符合資料類型的要求, Vue 會在瀏覽器的控制台顯示錯誤訊息來提醒開發者,在團隊開發中是個很實用的功能,其中 Vue 內建能夠檢查的 type 屬性有 String 、 Number 、 Boolean 、 Array 、 Object 、 Date 、 Function 、 Symbol 。

如何指定 Props 的資料類型?

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


上一篇
Day15 Vue 元件間的傳遞 Props (上)
下一篇
Day17 Vue 元件間的事件傳遞 Emit
系列文
新手學習Vue.js與實作之旅17
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言