🔸<slot>
╱🚧 under construction -> default slot
named slot:可控制內容的插入位置。
fallback content:
<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>
使用 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?