【问题标题】:Rendering child elements with LitElement ( light DOM and slots )使用 LitElement 渲染子元素(轻 DOM 和插槽)
【发布时间】:2021-03-19 07:15:10
【问题描述】:
【问题讨论】:
标签:
children
lit-element
slot
【解决方案1】:
要在 Lit 版本 2 中直接在 DOM 树(又名 light-dom)中渲染元素,请使用从 lit/html.js 导出的 render(lit 从它的 lit-html 版本导入它,有关详细信息,请参阅 https://lit.dev/):
<script type=module>
// or from 'lit' and 'lit/html.js' respectively:
import { LitElement, html } from 'https://unpkg.com/lit?module';
import { render } from 'https://unpkg.com/lit/html.js?module';
class EgTime extends LitElement{
connectedCallback(){
super.connectedCallback();
render(this.time(), this);
}
time(){
const now = new Date();
return html`<time datetime="${ now.toISOString() }">time ${ now.toLocaleTimeString() } ${ now.toLocaleDateString() }</time>`;
}
render(){
return html`<hr> ::slotted( <slot>~~~</slot> ) <hr>`;
}
}
customElements.define('eg-time', EgTime);
</script>
<eg-time style="position:fixed;inset:auto 3rem 3rem auto;background:#fff;padding:1rem;border:1px solid #000;">
...
</eg-time>
【解决方案2】:
在 light Dom 中,您的 render() 将修改您的组件在安装之前的先前子节点。
一种方法可以保存调用 connectedCallback 之前的任何内容。
考虑以下示例
export class Text extends LitElement {
createRenderRoot() {
return this;
}
connectedCallback() {
super.connectedCallback();
this._textOverride = this.innerText.trim();
}
render() {
return html`
<strong>${this._textOverride}</strong>
`;
}
}