39
Vue 3 學習之旅
元件系統
具名插槽:多個內容分發點
·6 分鐘閱讀·元件系統
摘要
具名插槽讓我們能夠在同一個元件中定義多個插槽,並為每個插槽指定名稱。這使得複雜的內容分發變得更加清晰和可控。
定義與說明
具名插槽的特點:
- • 可以在子元件中定義多個不同名稱的插槽
- • 父元件可以精確地將內容分發到指定的插槽
- • 未指定名稱的插槽會被視為預設插槽
- • 支援簡寫語法 (#) 來提高程式碼簡潔性
使用場景:
具名插槽特別適合需要多個內容分發點的複雜元件,例如:
- • 頁面佈局(頁首、側邊欄、主內容、頁尾)
- • 對話框(標題、內容、按鈕區)
- • 卡片元件(標題、圖片、描述、操作區)
實作範例
Dialog.vue (子元件)
<template>
<div class="dialog">
<header class="dialog-header">
<slot name="header">
<h2>預設標題</h2>
</slot>
</header>
<div class="dialog-body">
<slot name="body">
<p>預設內容</p>
</slot>
</div>
<footer class="dialog-footer">
<slot name="footer">
<button>確定</button>
</slot>
</footer>
</div>
</template>
App.vue (父元件)
<template>
<Dialog>
<template v-slot:header>
<h2 class="text-xl font-bold">
確認刪除
</h2>
</template>
<template #body>
<p>
確定要刪除這個項目嗎?此操作無法復原。
</p>
</template>
<template #footer>
<div class="flex space-x-4">
<button class="btn-danger">
確認刪除
</button>
<button class="btn-cancel">
取消
</button>
</div>
</template>
</Dialog>
</template>
結論
具名插槽是 Vue 元件系統中一個強大的功能,它讓我們能夠建立更加靈活和可重用的元件。透過為不同的插槽命名,我們可以精確控制內容的分發位置,同時保持元件的結構清晰。這對於建立複雜的 UI 元件特別有用。
具名插槽 內容分發 元件組合