为什么在 WebComponent 中使用 <template>?

Why use the <template> in WebComponent?

提问人:Kepas 提问时间:7/14/2023 最后编辑:Kepas 更新时间:7/14/2023 访问量:35

问:

我看到了很多 Web 组件的例子,每个人都使用模板标签来绘制屏幕。是否有理由使用模板标签而不是 <div> 或 <section> 等标签?

这是示例代码

#render()
{
    if (!this.#template_node) this.#template_node = this.#get_default_template();

    this.shadowRoot.appendChild(this.#template_node.content.cloneNode(true));
}

#get_default_template()
{
    const template = document.createElement("template");
    template.innerHTML = `<p>Test Webcomponent</p>`

    return template;
}
JavaScript 模板

评论


答:

1赞 jcbirdwell 7/14/2023 #1

据我了解,模板元素不会与页面的其余部分一起呈现,但它们的内容可用于克隆和/或稍后使用 js 添加。https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template

评论

0赞 Kepas 7/14/2023
我明白这一点。但是,即使组件使用 div 标签而不是模板标签,在组件连接到 DOM 之前它不会在屏幕上绘制不是一样吗?
0赞 jcbirdwell 7/14/2023
是的。因此,使模板有用,因为它们可以在不渲染的情况下附加。使用它们也只是增加了代码的清晰度,而不是让一堆隐藏的 div 服务于类似的目的。