父子組件通訊的場景不少,例如:javascript
父 -> 子:頁面上(父)有兩個自定義按鈕(子),每一個按鈕的顏色不同;css
子 -> 父:點擊頁面(父)上按鈕(子),頁面(父)上一個數字發生了遞增html
咱們以上面講到的自定義按鈕爲例子來講明父組件如何調用子組件。vue
定義一個自定義按鈕組件:wds-button
。若是想使用它,能夠在html中這麼寫:java
<wds-button><wds-button>
獲得的效果以下:app
具體實現邏輯:函數
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style scoped> .wds-button{ line-height: 1; white-space: nowrap; cursor: pointer; background: #fff; border: 1px solid #bfcbd9; color: #1f2d3d; outline: none; margin: 0; padding: 10px 15px; font-size: 14px; border-radius: 4px; } </style> </head> <body> <div id="app"> <wds-button></wds-button> </div> </body> <template id="template-wds-button"> <button class="wds-button">默認按鈕</button> </template> <script src="http://cdn.bootcss.com/vue/2.1.10/vue.min.js"></script> <script> var wdsButton = { template: '#template-wds-button' } var vm = new Vue({ el: '#app', components: { 'wds-button': wdsButton } }) </script> </html>
若是咱們想實如今頁面上顯示兩個不一樣顏色自定義按鈕呢?咱們可能但願經過以下的方式來使用這個自定義按鈕,來實現效果。spa
<wds-button color="red"></wds-button> <wds-button color="yellow"></wds-button>
若是說wds-button
是子組件,那麼使用該組件的當前頁面則爲父組件。這裏的color是子組件的自定義屬性名(由於用法和html的標籤屬性的用法一致),而"red"、"yellow"是父組件傳遞給子組件的值。相似於函數的形參和實參。3d
所以若是按照上面的那種調用組件的方法,總結一下:code
子組件得擁有一個自定義的屬性:color;
父組件經過子組件(wds-button)中的自定義屬性名(color),能夠將不一樣的值(red/yellow)傳遞給子組件,從而達到複用子組件的效果。
那具體在代碼層面如何實現呢?
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style scoped> .wds-button{ line-height: 1; white-space: nowrap; cursor: pointer; background: #fff; border: 1px solid #bfcbd9; color: #1f2d3d; outline: none; margin: 0; padding: 10px 15px; font-size: 14px; border-radius: 4px; } .wds-button--red{ background: red; } .wds-button--yellow{ background: yellow; } </style> </head> <body> <div id='app'> <wds-button></wds-button> <wds-button color="red"></wds-button> <wds-button color="yellow"></wds-button> </div> </body> <template id='template-wds-button'> <button v-bind:class="[color ? 'wds-button wds-button--' + color: 'wds-button']">默認按鈕</button> </template> <script src="http://cdn.bootcss.com/vue/2.1.10/vue.min.js"></script> <script> var wdsButton = { props: { color: { type: String, default: '' } }, template: '#template-wds-button' } var vm = new Vue({ el: '#app', components: { 'wds-button': wdsButton } }) </script> </html>
這裏子組件的JS對象中須要申明一個屬性(props
),告知調用者暴露的自定屬性名字是什麼(這裏props裏又一個屬性color),同時給出對應的類型和默認值(type & default)。
var wdsButton = { props: { color: { type: String, default: '' } }, template: '#template-wds-button' }
同時在視圖模版中,給自定義按鈕綁定一個css class,其值由屬性color的值來定。
<template id='template-wds-button'> <button v-bind:class="[color ? 'wds-button wds-button--' + color: 'wds-button']">默認按鈕</button> </template>
按照上面的方式來,就實現了一個可以傳入顏色屬性的自定義的組件按鈕。同時這個wds-button
組件能夠擁有了了一份屬於它本身的相似於接口的文檔:
Props
參數 | 說明 | 類型 | 可選值 | 默認 |
---|---|---|---|---|
color | 按鈕顏色 | String | red/color | — |