子組件接收父組件的參數的時候,props注冊接收的參數
props:['count']
子組件可以對接收的參數校驗。
例如規定接收的count參數要求是String
props:{count:String}如果count是別的類型就會報錯
組件的參數校驗
組件的參數校驗指的是什么呢?你父組件向子組件傳遞的內容,子組件有權對這個內容進行一些約束,這個約束我們可以把它叫做參數的校驗。
<div id="root"> <child content="hello world"></child></div>Vue.component('child',{ props: ['content'], template: '<div>{{content}}</div>'})let vm = new Vue({ el: '#root',}) 現在有這樣一個需求,父組件調用子組件的時候,傳遞的這個content,我要做一些約束,要求它我傳遞過來的content必須是一個字符串,我們該怎么實現呢?
<div id="root"> <child content="hello world"></child></div>Vue.component('child',{ props: { content: String //子組件接收到的 content 這個屬性,必須是一個字符串類型的 }, template: '<div>{{content}}</div>'})let vm = new Vue({ el: '#root',}) 組件接收到的content這個屬性,必須是一個字符串類型的,如果我需要的參數類型是字符串或者數組,又該怎么寫呢?
props: { content: [ String, Number ]}, content的類型,可以用數組來表示。
content其實還有更復雜的用法:
props: { content: { type: Sring, required: true, //必傳 default: 'default value', //默認顯示,非必傳會顯示 validator(value){ //檢測 content 的長度,如果長度大于 5,正常顯示,如果長度小于 5 則報錯 return (value.length > 5) } }}非props特性
說到非props特性,它一定和props特性相對應。
props特性:當你的父組件使用子組件的時候,通過屬性向子組件傳值的時候,恰好子組件里面聲明了對父組件傳遞過來的屬性的一個接收,也就是說父子組件有個對應關系,如果你這么寫我們就把叫做props特性
props特性的特點是,如下圖:
新聞熱點
疑難解答
圖片精選