🔸<slot>
╱🚧 under construction -> default slot
使用方式
📁 自訂元素的 <template> 中:定義 <slot> 的位置(也可以放 named slot)
<template id="my-component-template">
<style>
.container {
border: 1px solid blue;
padding: 10px;
}
</style>
<div class="container">
<p>This is some default text.</p>
<!-- ⭐️ 1️⃣ 決定 <slot> 位置 -->
<slot></slot>
<p>This is more default text.</p>
</div>
</template>📁 HTML:在自訂元素標籤 (如:<my-component>) 中加入 HTML 內容
<my-component>
<!-- ⭐️ 2️⃣ 加入 HTML 內容 -->
<!-- 沒有指定插槽名稱的,會放入 default slot -->
<h2>This is the slotted content!</h2>
<p>This is another paragraph inside the slot.</p>
</my-component>但最終呈現的結果則由自訂元素 <template> 內所定義的結構決定。
使用 slotchange 事件
slotchange 事件當 <slot> 的內容發生變化時(如插入或移除 slotted nodes ),就會觸發 slotchange 這個事件。你可以使用這個事件來監聽 slotted nodes 的變化,並執行相應的操作。
constructor() {
super();
let root = this.attachShadow({ mode: 'open' }); // root == this.shadowRoot
// ... (其他程式碼)
// ⭐️ "slotchange" event
const slot = root.querySelector('slot');
slot.addEventListener('slotchange', (event) => {
console.log('Slot 內容發生變化!');
const slottedNodes = slot.assignedNodes();
console.log('Slotted nodes:', slottedNodes);
});
}Last updated
Was this helpful?