我试图让我的 Web 组件也通过事件与外部通信。到目前为止,发出事件似乎没问题,但由于某种原因无法接收事件。
我已经尝试了 和 的许多变体bubbles
,composed
并将发射器附加到网络组件的shadowRoot
,但它不起作用。
我在这里缺少什么?(还有:为什么下面容器的背景色不是黄色?)
class HookbanContainer extends HTMLElement {
connectedCallback() {
const template = document.createElement("template")
template.innerHTML = /* html */ `
<style>
:host {
background-color: yellow;
}
</style>
<slot></slot>
`
const shadowRoot = this.attachShadow({ mode: "open" })
shadowRoot.appendChild(template.content.cloneNode(true))
shadowRoot.addEventListener(
"hookban-test",
(e) => console.log("test", e)
)
}
}
customElements.define("hookban-container", HookbanContainer)
<hookban-container>
<p>hello</p>
</hookban-container>
<button>Trigger Event</button>
<script>
const triggerEvtButton = document.querySelector("button")
triggerEvtButton.onclick = () => {
document.dispatchEvent(
new CustomEvent("hookban-test", {
bubbles: true,
composed: true,
detail: {
content: "test"
}
})
)
}
</script>
分派到的事件
document
不会在任何子元素(包括开放的影子根)上触发,而是document
在您的 Web 组件中监听: