【发布时间】:2022-09-13 23:35:47
【问题描述】:
我有一个Custom Element,它应该有很多 HTML 子级。我在课堂上初始化它时有this problemconstructor(结果不能有孩子)。我理解为什么并且知道如何解决它。但是我现在应该如何围绕它设计我的课程呢?请考虑以下代码:
class MyElement extends HTMLElement {
constructor() {
super();
}
// Due to the problem, these codes that should be in constructor are moved here
connectedCallback() {
// Should have check for first time connection as well but ommited here for brevity
this.innerHTML = `<a></a><div></div>`;
this.a = this.querySelector("a");
this.div = this.querySelector("div");
}
set myText(v) {
this.a.textContent = v;
}
set url(v) {
this.a.href = v;
}
}
customElements.define("my-el", MyElement);
const frag = new DocumentFragment();
const el = document.createElement("my-el");
frag.append(el); // connectedCallback is not called yet since it's not technically connected to the document.
el.myText = "abc"; // Now this wouldn't work because connectedCallback isn't called
el.url = "https://www.example.com/";
由于MyElement 将在列表中使用,因此已预先设置并插入DocumentFragment。你怎么处理这个?
目前我正在保留一个预先连接的属性列表,并在实际连接时设置它们,但我无法想象这是一个好的解决方案。我还想到了另一种解决方案:有一个(好吧,我刚刚意识到没有什么可以阻止您自己调用init 方法connectedCallback)在做任何事情之前必须手动调用它,但我自己没有看到任何需要这样做的组件,它类似于上面提到的upgrade弱点文章:
不得检查元素的属性和子元素,因为在非升级情况下不会出现任何内容,并且依赖升级会使元素的可用性降低。
【问题讨论】:
-
您需要 (a) DOM 在其中设置内容。您可以在其中创建一个带有
<a></a>的 shadowDOM
标签: javascript html web-component custom-element