【发布时间】:2021-10-04 00:43:24
【问题描述】:
在设计自定义元素时,我了解模板在性能方面的优势,但对于仅在一个元素中使用的结构,我很难理解在元素类定义本身的 constructor() 中构建 html 的缺点.
换句话说,这样做有什么缺点:
const myTemplate = document.createElement("template");
myTemplate.innerHTML = `<p>my text</p>`;
customElements.define( 'my-elem', class extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" });
this.shadowRoot.appendChild(myTemplate.content.cloneNode(true));
}
})
在此:
customElements.define( 'my-elem', class extends HTMLElement {
constructor() {
super();
let myP = document.createElement("p");
let myText = document.createTextNode("my text");
myP.appendChild(myText);
this.attachShadow({ mode: "open" });
this.shadowRoot.appendChild(myP);
}
})
...当后一个选项 (a) 保留使用 createElement 的优势,并且 (b) 有助于防止在元素定义范围之外定义模板时引入的潜在封装问题?
我还知道,我可以使用createElement 而不是上面示例中的innerHTML 构建模板,但这有可能引入更多在元素定义范围之外定义的变量。
【问题讨论】:
标签: javascript html web-component custom-element html-templates