Vue v-slot
我們需要使用 v-slot
指令來引用命名插槽。
命名插槽允許更精細地控制內容在子元件模板中的放置位置。
命名插槽可用於建立更靈活和可重用的元件。
在使用 v-slot
和命名插槽之前,讓我們看看在元件中使用兩個插槽會發生什麼
示例
App.vue
:
<h1>App.vue</h1>
<p>The component has two div tags with one slot in each.</p>
<slot-comp>'Hello!'</slot-comp>
SlotComp.vue
:
<h3>Component</h3>
<div>
<slot></slot>
</div>
<div>
<slot></slot>
</div>
執行示例 »
在一個元件中有兩個插槽時,我們可以看到內容只是出現在了兩個地方。
v-slot 和命名插槽
如果我們一個元件中包含多個 <slot>
,但我們想控制內容應該出現在哪個 <slot>
中,我們需要給插槽命名,並使用 v-slot
將內容傳送到正確的位置。
示例
為了能夠區分插槽,我們給它們起了不同的名字。
SlotComp.vue
:
<h3>Component</h3>
<div>
<slot name="topSlot"></slot>
</div>
<div>
<slot name="bottomSlot"></slot>
</div>
現在我們可以使用 v-slot
在 App.vue
中將內容定向到正確的插槽。
App.vue
:
<h1>App.vue</h1>
<p>The component has two div tags with one slot in each.</p>
<slot-comp v-slot:bottomSlot>'Hello!'</slot-comp>
執行示例 »
預設插槽
如果你有一個沒有名字的 <slot>
,那個 <slot>
將是標記為 v-slot:default
的元件,或者未標記為 v-slot
的元件的預設值。
要了解其工作原理,我們只需對之前的示例進行兩個小改動
示例
SlotComp.vue
:
<h3>Component</h3>
<div>
<slot name="topSlot"></slot>
</div>
<div>
<slot name="bottomSlot"></slot>
</div>
App.vue
:
<h1>App.vue</h1>
<p>The component has two div tags with one slot in each.</p>
<slot-comp v-slot:bottomSlot>'Hello!'</slot-comp>
執行示例 »
如前所述,我們可以使用 v-slot:default
的預設值來標記內容,這樣更清楚地表明內容屬於預設插槽。
示例
SlotComp.vue
:
<h3>Component</h3>
<div>
<slot></slot>
</div>
<div>
<slot name="bottomSlot"></slot>
</div>
App.vue
:
<h1>App.vue</h1>
<p>The component has two div tags with one slot in each.</p>
<slot-comp v-slot:default>'Default slot'</slot-comp>
執行示例 »
在 <template> 中使用 v-slot
如你所見,v-slot
指令可以用作元件標籤中的屬性。
v-slot
也可以用在 <template>
標籤中,將較大的內容塊定向到特定的 <slot>
。
示例
App.vue
:
<h1>App.vue</h1>
<p>The component has two div tags with one slot in each.</p>
<slot-comp>
<template v-slot:bottomSlot>
<h4>To the bottom slot!</h4>
<p>This p tag and the h4 tag above are directed to the bottom slot with the v-slot directive used on the template tag.</p>
</template>
<p>This goes into the default slot</p>
</slot-comp>
SlotComp.vue
:
<h3>Component</h3>
<div>
<slot></slot>
</div>
<div>
<slot name="bottomSlot"></slot>
</div>
執行示例 »
我們使用 <template>
標籤將某些內容定向到特定的 <slot>
,因為 <template>
標籤不會被渲染,它只是內容的佔位符。你可以透過檢查生成的頁面來看到這一點:你找不到模板標籤。
v-slot 簡寫 #
v-slot:
的簡寫是 #
。
這意味著
<slot-comp v-slot:topSlot>'Hello!'</slot-comp>
可以寫成
<slot-comp #topSlot>'Hello!'</slot-comp>
示例
App.vue
:
<h1>App.vue</h1>
<p>The component has two div tags with one slot in each.</p>
<slot-comp #topSlot>'Hello!'</slot-comp>
SlotComp.vue
:
<h3>Component</h3>
<div>
<slot name="topSlot"></slot>
</div>
<div>
<slot name="bottomSlot"></slot>
</div>
執行示例 »