在講解以前,先閉上眼睛理解下下面這兩個概念:組件模板||組件標籤spa
我的理解:
是對組件的擴展,經過slot插槽向組件內部指定位置傳遞內容,經過slot能夠父子傳參;code
開發背景(slot出現時爲了解決什麼問題):
正常狀況下,<Child><span style=」color:red;」>hello world</span></Child>
在組件標籤Child中的span標籤會被組件模板template內容替換掉,當想讓組件標籤Child中內容傳遞給組件時須要使用slot插槽;開發
Slot的通俗理解模板
是「佔坑」,在組件模板中佔好了位置,當使用該組件標籤時候,組件標籤裏面的內容就會自動填坑(替換組件模板中<slot>位置),當插槽也就是坑<slot name=」mySlot」>有命名時,組件標籤中使用屬性slot=」mySlot」的元素就會替換該對應位置內容;擴展
Slot使用
一、組件中有單個或多個未命名slot標籤時,以下:命名
<Child><span style=」color:red;」>hello world</span></Child> <template> <div> <slot></slot> <slot style=」color:blue;」 >這是在slot上添加了樣式</slot> <slot name=」mySlot」>這是擁有命名的slot的默認內容</slot> </div> </template>
會輸出:兩個紅色的hello world,以及一個使用slot的默認內
注意:在slot標籤添加樣式無效。
擁有命名的插槽不能被不含slot屬性的標籤內容替換,會顯示slot的默認值(具名slot具備對應性);樣式
二、組件中有多個命名的slot插槽時,能夠實現父組件對子組件的指定位置顯示內容或傳參,以下:di
<Child> <span slot="header">hello world</span> <span slot="main">hello world</span> <span slot="footer">hello world</span> <span slot="other">{{otherData}}</span> </Child> <template> <div> <slot name=」header」>這是擁有命名的slot的默認內容</slot> <slot name=」main」>這是擁有命名的slot的默認內容</slot> <slot name=」footer」>這是擁有命名的slot的默認內容</slot> <slot name=」other」>這是擁有命名的slot的默認內容</slot> </div> </template>