Vue 插槽
插槽是 Vue 中一個強大的功能,它允許更靈活和可重用的元件。
我們使用 Vue 中的插槽將父元件的內容傳送到子元件的 <template>
中。
插槽
到目前為止,我們只在 <template>
中將元件用作自閉合標籤,例如:
App.vue
:
<template>
<slot-comp />
</template>
相反,我們可以使用開閉標籤,並在其中放置一些內容,例如一段文字:
App.vue
:
<template>
<slot-comp>Hello World!</slot-comp>
</template>
但要接收 'Hello World!' 並將其顯示在我們的頁面上,我們需要在元件中使用 <slot>
標籤。<slot>
標籤充當內容的佔位符,因此在應用程式構建後,<slot>
將被髮送給它的內容替換。
插槽作為卡片
插槽也可用於包裝大塊的動態 HTML 內容,以獲得卡片式外觀。
之前我們透過 props 傳送資料來建立元件內部的內容,現在我們可以直接將 HTML 內容作為內容傳送到 <slot>
標籤中。
示例
App.vue
:
<template>
<h3>Slots in Vue</h3>
<p>We create card-like div boxes from the foods array.</p>
<div id="wrapper">
<slot-comp v-for="x in foods">
<img v-bind:src="x.url">
<h4>{{x.name}}</h4>
<p>{{x.desc}}</p>
</slot-comp>
</div>
</template>
當內容進入帶有 <slot>
的元件時,我們在 <slot>
周圍使用 div 並本地化樣式化 <div>
,以在內容周圍建立卡片式外觀,而不會影響我們應用程式中的其他 div。
SlotComp.vue
:
<template>
<div> <!-- This div makes the card-like appearance -->
<slot></slot>
</div>
</template>
<script></script>
<style scoped>
div {
box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
border-radius: 10px;
margin: 10px;
}
</style>
執行示例 »
可以重用生成卡片式框架內容的元件來建立不同的元素,但它們都帶有相同的卡片式框架。
在這個例子中,我們使用與食物項相同的元件來建立一個頁尾。
示例
App.vue
:
<template>
<h3>Reusable Slot Cards</h3>
<p>We create card-like div boxes from the foods array.</p>
<p>We also create a card-like footer by reusing the same component.</p>
<div id="wrapper">
<slot-comp v-for="x in foods">
<img v-bind:src="x.url">
<h4>{{x.name}}</h4>
</slot-comp>
</div>
<footer>
<slot-comp>
<h4>Footer</h4>
</slot-comp>
</footer>
</template>
執行示例 »
備用內容
如果沒有為元件提供內容,我們可以在 <slot>
中設定備用內容。
示例
此應用程式中的第一個元件沒有提供內容,因此會渲染備用內容。
App.vue
:
<template>
<h3>Slots Fallback Content</h3>
<p>A component without content provided can have fallback content in the slot tag.</p>
<slot-comp>
<!-- Empty -->
</slot-comp>
<slot-comp>
<h4>This content is provided from App.vue</h4>
</slot-comp>
</template>
SlotComp.vue
:
<template>
<div>
<slot>
<h4>This is fallback content</h4>
</slot>
</div>
</template>
執行示例 »