Web 组件:如何使用 shadowRoot.querySelector 访问开槽元素

Web Components: how to access a slotted element using shadowRoot.querySelector

您好,我是 Web 组件概念的新手。我想知道我们是否可以使用 shadowRoot.querySelector

访问开槽元素

我已经实现了一个输入字段作为动态设置一些值的插槽。并在其中添加一个 class 'column-title'。我正在尝试像这样访问 connectedCallback() 中的这个元素

var titleInput = this.shadowRoot.querySelector('.column-title')

但它 returns 无效。

请帮忙。

我不确定问题出在哪里,但您应该能够使用 querySelector 及其 class 获得一个插槽。我在下面模拟了一个例子。

控制台将打印出对插槽的引用。如果你附加一个 class 只是为了找到插槽,那么最好设置一个 id(假设它在影子根内)并用 this.shadowRoot.getElementById('my-slot-id')

找到它

customElements.define('blue-box',
  class extends HTMLElement {
    constructor() {
      super();
      var template = document
        .getElementById('blue-box')
        .content;
      const shadowRoot = this.attachShadow({
          mode: 'open'
        })
        .appendChild(template.cloneNode(true));
    }
    
    connectedCallback() {
     console.log(this.shadowRoot.querySelector('slot.target-slot'));
    }
  });
<template id="blue-box">
  <style>
  .blue-border {
    border: 2px solid blue;
    padding: 5px;
    margin: 5px;
  }
  </style>
  <div class='blue-border'>
    <slot name='interior' class='target-slot'>NEED INTERIOR</slot>
  </div>
</template>

<blue-box>
  <span slot='interior'>My interior text</span>
</blue-box>
<blue-box>
  <span slot='interior'>
  Check Here: <input type='checkbox'>
  </span>
</blue-box>

离开@royyko 的回应。这里更好的答案是不要给出 class 或 id 来抢占插槽......使用已经提供的标识符,它的名称。为此,您需要执行以下操作 this.shadowRoot.querySelector('slot[name=interior]')