首页 > 解决方案 > 在自定义元素(Web 组件)中使用文档

问题描述

我有两个单独的自定义元素组件,如果我想对 ComponentA 中的 ComponentB 的元素做一些事情,那么最好的方法是什么?

索引.html

<body>

  <componentA>
    <div class="container">
     <p>I am component A</p>
     <p>abc</p>
    </div>
  </componentA>

  <componentB>
    <div class="container">
     <p>I am component B</p>
     <p></p> // Will set data between the p tag in componentA
    </div>
  </componentB>

</body>

组件A.js

...component template...

class ComponentA extends HTMLElement {

  constructor() {
    super();
    this.attachShadow({mode: 'open'});
    this.shadowRoot.appendChild(template.content.cloneNode(true));
  }

  connectedCallback() {

    this.setInnerTextToComponentBElement();

  }

  setInnerTextToComponentBElement(){

    // How to set componentB's second p tag innerText?

  }
}

customElements.define('componentA', ComponentA );

我曾想过使用 document.querySelector 来获取 componentB 元素并从那里开始......但这是最佳实践方式吗?

标签: javascriptweb-componentcustom-element

解决方案


我建议永远不要将两个组件捆绑在一起,除非允许开发人员使用这些组件来提供连接它们的方法。

通常元素之间的通信或互连由父级处理。我所知道的唯一能做到这一点的元素是<label>元素。如果这是 , 的父元素,<input>则它将焦点传递给子元素。<select><button><textarea>

但是要将它与兄弟元素一起使用,您必须将 的for属性设置<label>id另一个字段的属性。然后另一个领域需要有它的id集合。

我在这里回答了这样的问题: 如何在 Web 组件(本机 UI)之间进行通信?

一旦将两个组件绑定在一起,除非您编写额外的代码以允许分离,否则这些组件将不再单独使用。

相反,要么允许组件调度父组件将接收的事件,然后父组件将值传递给另一个组件。或者,按照<label for="">工作原理的示例进行操作。


推荐阅读