使用 Typescript 的 Litelements 中的静态 shadowRootOptions,将模式设置为打开或关闭

static shadowRootOptions in Litelements with Typescript, set mode to open or close

我目前正在使用 Litelements 研究 Webcomponents:在 Webcomponents 中,您可以通过将模式 属性 定义为 'open' 或 'closed' 来更改 shadowdom 的工作方式。在没有 LitElements 的香草 Javascript 中就像这样:

Javascript:

var shadow = this.attachShadow({mode: 'open'});

来自:https://developer.mozilla.org/en-US/docs/Web/API/Element/attachShadow

现在在 Litelements with Typescript 中是这样实现的:

打字稿:

export class MyWebcomponents extends LitElement {
  static shadowRootOptions = {...LitElement.shadowRootOptions, delegatesFocus: true};
}

来自:https://lit.dev/docs/components/shadow-dom/

he simplest way to customize the render root is to set the shadowRootOptions static property. The default implementation of createRenderRoot passes shadowRootOptions as the options argument to attachShadow when creating the component's shadow root. It can be set to customize any options allowed in the ShadowRootInit dictionary, for example mode and delegatesFocus.

老实说,我无法让它工作,我尝试了很多东西,比如:

打字稿:

static shadowRootOptions = {...{mode: 'open'}, delegatesFocus: true}; 

上面的尝试给我一个错误,我没有正确扩展 class LitElement。

打字稿:

static shadowRootOptions = {mode: 'open', delegatesFocus: true};

给我愚蠢的错误消息,只有 VS Code 和 Typescript 可以归结为错误的 class 扩展。

打字稿:

static shadowRootOptions = {{mode: 'open'}, delegatesFocus: true};

上面的尝试给了我一条消息,告诉我我没有正确扩展并且还抱怨语法。

然后我试图找出 LitElement.shadowRootOptions 是什么类型并提供类似的东西,但后来我陷入了提出更多问题的困境,并发现这个简单的 oneliner 更加晦涩难懂。 (是的,我确实阅读了传播语法,我想我理解了,我还根据传播语法阅读了这篇文章: )

所以为了让这个问题简单化:

任何人都可以为我指明正确的方向,告诉我如何编写语法才能使其有效吗?我只是希望能够按照要设置的方式将模式设置为打开或关闭。

非常感谢!

问候

亚历克斯

默认情况下,点亮元素以 open 模式运行。 所以 customLitElement.shadowRoot returns 影子根。

如果你想 运行 它处于关闭模式,请执行此方法:

 createRenderRoot() {
    return this;
 } 

<script type="module">
import {
  LitElement,
  html,
  css
} from "https://unpkg.com/lit-element/lit-element.js?module";

class ClosedEl extends LitElement {
  
 createRenderRoot() {
    return this;
 } 

 render() {
  return html`
      <h1>Example Closed</h1>
  `;
 }
}

class OpenedEl extends LitElement {

 render() {
  return html`
      <h1>Example Opened</h1>
  `;
 }
}

customElements.define("my-closed", ClosedEl);
customElements.define("my-opened", OpenedEl);

console.log(`ShadowRoot of closed El: ${document.getElementById('closed').shadowRoot}`);
console.log(`ShadowRoot of opened El: ${document.getElementById('opened').shadowRoot}`);

console.log(`Access to opened El: ${document.getElementById('opened').shadowRoot.innerHTML}`);
</script>
<my-closed id="closed"></my-closed>
<my-opened id="opened"></my-opened>