1

我尝试使用 Lit 2.0 构建复合组件,但将数据作为属性传递给插槽似乎是不可能的。

  <my-accordion>
    <my-accordion-title>Title</my-accordion-title>
    <my-accordion-content>Content</my-accordion-content>
  </my-accordion

如何将“扩展”属性传递给自定义元素插槽?

这是我的自定义元素:

@customElement("my-accordion")
export class MyAccordion extends LitElement {

  @property()
  extended: boolean = false;

  toggleExtend(){
     this.extended = !this.extended
  }

  render() {
    return html`
      <div @click=${this.toggleExtend}>
        <slot .extended=${this.extended}></slot>
      </div>
    `;
  }
}


@customElement("my-accordion-title")
export class MyAccordionTitle extends LitElement {
  // want to access parent node extended property here
  render() {
    return html`
      <div>
        <slot></slot>
      </div>
    `;
  }
}
4

1 回答 1

1

要将extended属性分配给插槽子元素,请获取插槽元素的assignedElements()数组。

@customElement("my-accordion")
export class MyAccordion extends LitElement {

  @property()
  extended: boolean = false;

  toggleExtend(){
     this.extended = !this.extended
  }

  updated(changed: PropertyValues<this>) {
    if (changed.has('extended'))
      this.extendedChanged()
  }

  extendedChanged() {
    for (const child of this.slot.assignedElements()) {
      if (child instanceof MyAccordionTitle)
        child.extended = this.extended;
    }
  }

  @query('slot') slot: HTMLSlotElement | null;
  
  render() {
    return html`
      <div @click=${this.toggleExtend}>
        <slot></slot>
      </div>
    `;
  }
}


@customElement("my-accordion-title")
export class MyAccordionTitle extends LitElement {
  // want to access parent node extended property here
  render() {
    return html`
      <div>
        <slot></slot>
      </div>
    `;
  }
}

注意:将点击侦听器分配给<div>其他非交互式元素时,会涉及许多可访问性问题。因此通常建议使用一个<button>元素,或者在你的情况下可能是一个<details><summary>

于 2021-05-05T15:56:15.810 回答