当插槽在 lit-html 中没有子节点时做一些事情

Do something when slot does not have child nodes in lit-html

我想在广告位上没有内容时显示文本。

class List extends LitElement {
  public render() {
    return slot.length === 0 
      ? html`No content is available`
      : html`<slot></slot>`;
  }
}

我认为这可能有帮助:

render() {
   return html` <slot id="slot">No content is available</slot> 

`;}

firstUpdated(){
      const slot = this.shadowRoot.querySelector("#slot");
      this.slt = slot.assignedNodes();
      if (this.slt.length===0){
        console.log('No content is available')
      } else {
        console.log('Content available', this.slt)
      }
}

除非渲染槽元素,否则不能槽的指定节点。这就是为什么首先需要渲染它的原因。之后有很多方法可以隐藏它。另一种方法是在它的父级检测它并将插槽元素的 nr 作为 属性.

传递

Demo