抄Mdn 原网页
This article explains how you can use the <template> and <slot> elements to create a flexible template that can then be used to populate the shadow DOM of a web component.
这编文章告诉你如何使用<template> 和 <slot> 来做一个可以填充在shadow dom中的灵活的模板;
When you have to reuse the same markup structures repeatedly on a web page, it makes sense to use some kind of a template rather than repeating the same structure over and over again. This was possible before, but it is made a lot easier by the HTML <template> element (which is well-supported in modern browsers). This element and its contents are not rendered in the DOM, but it can still be referenced using JavaScript.
当你在一个网页中不得不重复使用同样标签结构时。看起来使用多种模板会比重复使用同样的结构好。现在这个是有可能的,使用html <template> 元素会使事情变得容易多了。(<template> 已经被现代浏览器支持了)_. element 和它的内容不会被渲染到dom中,但可以被javascript 引用。
使用例子
<template id="my-paragraph">
<p>My paragraph</p>
</template>
let template = document.getElementById('my-paragraph');
let templateContent = template.content;
document.body.appendChild(templateContent);
Although trivial, you can already start to see how this could be useful.
尽管这个是很无聊的,但你已经开始看到它可以是非常的有效的。
Using templates with the web components 在网络组件中使用模板
Templates are useful on their own, but they work even better with web components. Let's define a web component that uses our template as the content of its shadow DOM. We'll call it :
模板是有用的,但它们在网络组件中能发挥更大的用处。让我们定义一个网络组件,这个组件使用了我们的模板作为它的shadow DOM的内容;
customElements.define('my-paragraph',
class extends HTMLElement {
constructor() {
super();
let template = document.getElementById('my-paragraph');
let templateContent = template.content;
const shadowRoot = this.attachShadow({mode: 'open'})
.appendChild(templateContent.cloneNode(true));
}
}
);