You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Polymer嵌套Shadow DOM(v1)自定义元素事件冒泡监听问题咨询

你的理解是对的,但需要修正事件触发的代码写法

首先明确:你的核心思路完全没问题——最外层的应用组件确实可以监听到最内层评分组件触发的自定义事件,但前提是你要正确配置自定义事件的参数(你当前的代码写法有个小错误)。

先修正你的事件触发代码

你现在把事件的bubbles和composed配置放在了dispatchEvent的第二个参数里,这是不正确的。正确的做法是把这些配置作为CustomEvent构造函数的第二个参数,然后将创建好的事件对象传给dispatchEvent:

错误写法:

this.dispatchEvent(new CustomEvent('custom-event'), { bubbles:true, composed:true });

正确写法:

this.dispatchEvent(new CustomEvent('custom-event', { bubbles: true, composed: true }));

为什么这样配置能让外层组件监听到?

Shadow DOM默认会隔离事件传播,要让事件穿透Shadow DOM边界到达外层组件,必须同时满足两个条件:

  • bubbles: true:开启事件的冒泡特性,让事件能沿着DOM树向上传播
  • composed: true:允许事件突破Shadow DOM的封装边界,进入到外层的DOM上下文(包括外层组件的Shadow DOM或者主文档DOM)

只要你的评分组件用正确的代码触发事件,外层的应用组件就可以正常监听到这个custom-event。

应用组件的监听方式示例

你可以在应用组件的模板里直接绑定事件:

<dom-module id="app-component">
  <template>
    <comment-component @custom-event="_handleCustomEvent"></comment-component>
  </template>
  <script>
    class AppComponent extends Polymer.Element {
      static get is() { return 'app-component'; }
      _handleCustomEvent(e) {
        console.log('收到评分组件的事件:', e.detail);
      }
    }
    customElements.define(AppComponent.is, AppComponent);
  </script>
</dom-module>

或者通过JavaScript手动添加监听:

// 在应用组件的connectedCallback里
connectedCallback() {
  super.connectedCallback();
  this.shadowRoot.querySelector('comment-component')
    .addEventListener('custom-event', this._handleCustomEvent.bind(this));
}

内容的提问来源于stack exchange,提问作者John Gorter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:11:49