javascript - 在自定义元素(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 元素并从那里开始......但这是最佳实践方式吗?
解决方案
我建议永远不要将两个组件捆绑在一起,除非允许开发人员使用这些组件来提供连接它们的方法。
通常元素之间的通信或互连由父级处理。我所知道的唯一能做到这一点的元素是<label>
元素。如果这是 , 的父元素,<input>
则它将焦点传递给子元素。<select>
<button>
<textarea>
但是要将它与兄弟元素一起使用,您必须将 的for
属性设置<label>
为id
另一个字段的属性。然后另一个领域需要有它的id
集合。
我在这里回答了这样的问题: 如何在 Web 组件(本机 UI)之间进行通信?
一旦将两个组件绑定在一起,除非您编写额外的代码以允许分离,否则这些组件将不再单独使用。
相反,要么允许组件调度父组件将接收的事件,然后父组件将值传递给另一个组件。或者,按照<label for="">
工作原理的示例进行操作。
推荐阅读
- react-redux - react-redux passport-google react-router:成功回调url重定向到'/'并且redux状态在页面重新加载时重置
- c# - C# 复制 RichTextbox 的表示然后将样式移植到 DataGridView
- javascript - 在 JavaScript 中,如何访问对象数组中的对象属性?
- autosar - 有人可以解释一下 PduR 在 AUTOSAR 中是什么意思吗?
- r - 识别 r 中聚合背后的频率计数
- python - 在 Google Colab 上播放视频
- github - 使 Github 页面可搜索
- scala - 带有非 http TCP 服务器的 Lightbend ssl-config
- node.js - 为什么不能在 Windows 上使用 npm 在子目录中调用 Cordova
- session - 是否可以在 Google Analytics 上跟踪每个用户的会话持续时间?