如何监听子元素的 Shadow dom 中触发的事件?

And*_*eas 6 html javascript web-component shadow-dom

我有两个网络组件,一个类似于列表项,另一个是容器。在列表项中有一个按钮,它调度 onclick 事件。两个组件都使用独立的 Shadow-dom。

<custom-list>
        <custom-list-item></custom-list-item>
        <custom-list-item></custom-list-item>
        <custom-list-item></custom-list-item>
</custom-list>
Run Code Online (Sandbox Code Playgroud)

如何在“自定义列表”中侦听“自定义列表项”中的按钮发出的事件?

Sup*_*arp 7

在容器自定义元素中<custom-list>,只需监听clickShadow DOM 根上的元素即可。click内部 Shadow DOM 中的元素发出的事件自然会冒泡到其容器。

this.shadowRoot.addEventListener( 'click', ev => console.log( ev.target.id ) )
Run Code Online (Sandbox Code Playgroud)

您还可以实现该handleEvent()方法来处理自定义元素内管理的所有事件:

this.shadowRoot.addEventListener( 'click', ev => console.log( ev.target.id ) )
Run Code Online (Sandbox Code Playgroud)
customElements.define( 'custom-list-item', class extends HTMLElement {
    constructor() {
        super()
        this.attachShadow( { mode: 'open' } )
            .innerHTML = `<button>Click</button>`             
    }  
} )

customElements.define( 'custom-list', class extends HTMLElement {
    constructor() {
        super() 
        this.attachShadow( { mode: 'open' } )
            .innerHTML = `
                <custom-list-item id=1></custom-list-item>
                <custom-list-item id=2></custom-list-item>
                <custom-list-item id=3></custom-list-item>` 
        this.shadowRoot.addEventListener( 'click', this )
    }
    handleEvent( ev ) {
        console.log( ev.target.id )
    }
} )
Run Code Online (Sandbox Code Playgroud)