我們來聊一下vue中的組件參數.
1.vue中組件參數
我們可以為組件的 prop 指定驗證要求,例如你知道的這些類型。如果有一個需求沒有被滿足,則 Vue 會在瀏覽器控制臺中警告你。這在開發一個會被別人用到的組件時尤其有幫助。
我們來看下最為簡單和常見的vue代碼
<div id="root"> <item content="hello"></item> </div> <script> Vue.component("item",{ props:["content"], template:"<div>{{content}}</div>" }) new Vue({ el:"#root" }) </script>這是一個最簡單的創建組件和父組件向子組件的例子,但是我們在是否可以考慮一下,如果我希望父組件向子組件傳遞參數的時候是個數字類型呢?又或者是布爾類型呢?所以我們在這里就必須要對父組件傳遞過來的參數做一個校驗。
<div id="root"> <item content="hello"></item> </div> <script> Vue.component("item",{ props:{ content:String }, template:"<div>{{content}}</div>" }) new Vue({ el:"#root" }) </script>我們對第一個例子的代碼進行了修改,我們把子組件中的props屬性,改為一種對象的形式,而且我們也約束了父組件傳遞過來的content為String類型,但是還會有這樣的一種情況出現,請看下面的代碼:
<div id="root"> <item content="1"></item> </div> <script> Vue.component("item",{ props:{ content:String }, template:"<div>{{content}}</div>" }) new Vue({ el:"#root" }) </script>我們改變了父組件中content的值等于1,那么我們就很自然的把content理解為數字類型,那么頁面就會出現報錯的提示.但是我們打開頁面后,并沒有瀏覽器報錯。這又是為什么呢?
在vue中,默認傳遞的值都是字符串,如果你想要傳遞一個數字,那么必須在content前面添加一個:
我們希望它出現報錯,那么我們就應該這么修改以上的代碼。
<div id="root"> <item :content="1"></item> </div> <script> Vue.component("item",{ props:{ content:String }, template:"<div>{{content}}</div>" }) new Vue({ el:"#root" }) </script>那么這個時候,VUE就會給我們一個代碼錯誤提示。如果我們希望它不報錯,那么我們修改一下content里面的類型
<div id="root"> <item :content="1"></item> </div> <script> Vue.component("item",{ props:{ content:Number }, template:"<div>{{content}}</div>" }) new Vue({ el:"#root" }) </script>
|
新聞熱點
疑難解答
圖片精選