Web 组件:如何从父组件访问子组件实例
编辑我在这个问题中遗漏了一些细节,但假设这两个元素已经定义。此外,在现实世界的问题中,DOM 树更大,子组件插入到父组件中。找到子组件没有问题。
我有两个 Web 组件:Parent
和 Child
。
我可能会在标记中使用这些组件,如下所示:
<parent-element>
<child-element></child-element>
</parent-element>
Child
组件具有我想要向父级公开的逻辑。
class Child extends HTMLElement {
constructor() {
...
}
publicMethod() {
console.log('call me from the parent component');
}
}
理想情况下,我想像这样从父级调用子方法:
class Parent extends HTMLElement {
constructor() {
...
}
someTrigger() {
const child = this.shadowRoot.querySelector('child-element');
child.publicMethod();
}
}
但这不起作用,因为 child
是一个 HTMLElement
,因为 querySelector()
API 返回 HTMLElement
,而不是 Web 组件实例。
有没有办法以类似的方式获取组件的实例?我希望能够遍历 Parent
组件影子树以查找特定的组件实例。
EDIT I've left out some details in this question, but assume that both of these elements are already defined. Also, in the real world problem, the DOM tree is bigger and the child component is slotted into the parent. There's no issue with finding the child component.
I have two web components: Parent
and Child
.
I might use these components in markup like this:
<parent-element>
<child-element></child-element>
</parent-element>
The Child
component has logic I want to expose to the parent.
class Child extends HTMLElement {
constructor() {
...
}
publicMethod() {
console.log('call me from the parent component');
}
}
Ideally, I'd like to call the child method from the parent like this:
class Parent extends HTMLElement {
constructor() {
...
}
someTrigger() {
const child = this.shadowRoot.querySelector('child-element');
child.publicMethod();
}
}
This doesn't work, though, since child
is an HTMLElement
, because the querySelector()
API returns an HTMLElement
and not the web component instance.
Is there a way I can get the component's instance in a similar fashion? I'd like to be able to traverse the Parent
components shadow tree to find a specific component instance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
小心
whenDefined
;它告诉您 Web 组件已定义,而不是在 DOM 中解析:
只要您保留
在 lightDOM 中,
和 ShadowDOM 与它们无关。Be careful with
whenDefined
;it tells you the Web Component was defined, NOT when it was parsed in the DOM:
As long as you keep the
<child-element>
in lightDOM,<slot>
and shadowDOM have nothing to do with them.