将数据(其目的是在 Shadow DOM 中显示)传递到自定义元素的更好方法是什么。这是通过使用属性还是插槽?
属性示例
class MyAttributeComponent extends HTMLElement {
constructor() {
super();
this.attachShadow({
mode: "open"
});
}
connectedCallback() {
const heading = this.getAttribute("heading");
this.shadowRoot.innerHTML = `
<h2>${heading}</h2>
`;
}
}
customElements.define("my-attribute-component", MyAttributeComponent);
<my-attribute-component heading="this is my attribute heading"></my-attribute-component>
老虎机示例
class MySlotComponent extends HTMLElement {
constructor() {
super();
this.attachShadow({
mode: "open"
});
this.shadowRoot.innerHTML = `
<slot></slot>
`;
}
}
customElements.define("my-slot-component", MySlotComponent);
<my-slot-component>
<h2>this is my slotted heading</h2>
</my-slot-component>
有没有“更好”他们都做不同的事情。
您注入的 HTML 由inshadowDOM
的样式设置样式slotted 内容由
<style>
IN lightDOM 设计或使用 ::slotted
进行开槽“皮肤”
要详细阅读
::slotted
,请参阅:::shadowDOM 插槽中嵌套子级的开槽 CSS 选择器
customElements.define("my-component", class extends HTMLElement {
constructor() {
super()
.attachShadow({mode:"open"})
.innerHTML =
`<style>h1 {border: 5px solid blue} `+
`*::slotted(h1){ background:pink }`+
`</style>` +
`<slot name="title"></slot>` +
`<h1></h1>`;
}
connectedCallback() {
this.shadowRoot.querySelector("h1").innerHTML = this.getAttribute("subtitle");
}
});
<style>
h1 {
border: 5px solid green
}
</style>
<my-component subtitle="Web Component World!">
<h1 slot="title">Hello,</h1>
</my-component>