插槽
一直對插槽不理解,今天學習,並整理一下,希望日后可以靈活運用。
(一)插槽內容
先簡單來個例子,看一下插槽的租作用。
1.1 不使用插槽
父組件中:
<div id="app"> <h1>這是父組件:{{msg}}</h1> <child-component>你好</child-component> </div>
子組件中:
<div> <h2>這是子組件,Child-Component</h2> </div>
結果:
結論:
父組件引用子組件時,在子組件內寫入:如(你好或者html),都不會顯示。
1.2 使用插槽
父組件中:
<div id="app"> <h1>這是父組件:{{msg}}</h1> <child-component>你好</child-component> </div>
子組件中:
<div> <h2>這是子組件,Child-Component</h2>
<slot></slot> </div>
結果:
結論:
Vue 實現了一套內容分發的 API,這套 API 的設計靈感源自 Web Components 規范草案,將 <slot>
元素作為承載分發內容的出口。當組件渲染的時候,<slot></slot>
將會被替換為“你好”。插槽內可以包含任何模板代碼,包括 HTML
1.3 包含html
父組件:
<div id="app"> <h1>這是父組件:{{msg}}</h1> <child-component> <span>slot 測試</span> </child-component> </div>
1.4 如果子組件沒有<slot>
如果子組件中沒有任何的<slot>,那么在父組件中引用子組件時,在子組件的起始標簽和結束標簽之間的任何內容都會被拋棄。
(二)后備內容
后備內容,即為沒有為插槽設置任何內容時,顯示的默認內容。
父組件:
沒有為插槽設置任何內容
<div id="app"> <h1>這是父組件:{{msg}}</h1> <child-component></child-component> </div>
子組件:
在子組件中,添加后備內容
<div> <h2>這是子組件,Child-Component</h2> <slot> <span>這是后備內容</span> </slot> </div>
結果:
但是如果設置插槽,后備內容則不會顯示。
(三)具名插槽
有的時候,我們需要多個插槽,例如:
父子件:
<div id="app"> <h1 style="text-align: center">這是父組件:{{msg}}</h1> <child-component> <template v-slot:header> <h3 style="text-align: center;color: blue">這是header部分</h3> </template> <p style="color: blueviolet;text-align: center">這是主題部分</p> <template v-slot:fooder> <h3 style="text-align: center;color: aqua">這是fooder部分</h3> </template> </child-component> </div>
子組件:
<div> <h2 style="text-align: center">這是子組件,Child-Component</h2> <slot name="header"></slot> <slot></slot> <slot name="footer"></slot> </div>
(四)作用域插槽
父組件中插槽中,可以取到子組件中數據。
父組件:
在v-slot添加元素上的特性被稱為插槽 prop
<div id="app"> <h2 >這是父組件!</h2> <child-slot> <template v-slot:default="user"> <p>父組件中,取子組件中的值:{{user.user.lastName}}</p> </template> </child-slot> </div>
子組件:
在<slot>中,綁定數據v-bind:user="user"
<div> <h2>這是子組件</h2> <span>FirstName:{{user.firstName}},LastName:{{user.lastName}}</span> <slot v-bind:user="user">{{user.lastName}}</slot> </div>
結果:
(五)獨占默認插槽的縮寫語法
當子組件中,只提供默認插槽時,組件的標簽才可以被當作插槽的模板來使用。這樣我們就可以把 v-slot
直接用在組件上:
<child-slot> <template v-slot:default="user"> <p>父組件中,取子組件中的值:{{user.user.lastName}}</p> </template> </child-slot>
也可以,簡寫為:
<child-slot> <template v-slot="user"> <p>父組件中,取子組件中的值:{{user.user.lastName}}</p> </template> </child-slot>