0

我有一个 Web 组件,我想调整其插槽的值。

不幸的是,我无法从中获得解析值。

我怎样才能做到这一点?

const template = document.createElement('template');
template.innerHTML = `
    <p><slot></slot></p>
`;

class MyComp extends HTMLElement {
    constructor() {
        super();
        this.root = this.attachShadow({mode: 'open'});
        this.root.appendChild(template.content.cloneNode(true));
    }

    connectedCallback() {
        const slot = this.shadowRoot.querySelector('slot');
        console.log('VALUE:', slot.innerText);  // always empty
    }
}

customElements.define('my-comp', MyComp);
<my-comp>abc</my-comp>

4

1 回答 1

2

您可以分配一个 EventListener 来监视 SLOT 更改

MDN 文档

customElements.define('my-element', class extends HTMLElement {
    constructor() {
      super();
      this.attachShadow({
        mode: 'open'
      }).appendChild(document.getElementById(this.nodeName).content.cloneNode(true));
    }

    connectedCallback() {
      this.listeners = [...this.shadowRoot.querySelectorAll("SLOT")].map(slot => {
        let name = "slotchange";
        let func = (evt) => {
          let nodes = slot.assignedNodes();
          console.log(`Slot ${slot.name} changed to ${nodes[0].outerHTML}`)
        }
        slot.addEventListener(name, func);
        return () => slot.removeEventListener(name, func); // return cleanup function!!!
      })
    }
    disconnectedCallback() {
      this.listeners.forEach(removeFunc => removeFunc());
    }
  });
<template id="MY-ELEMENT">
  <style>
    ::slotted(*) {
      background: yellow;
      margin: 0;
    }

    ::slotted(span) {
      color: red;
    }

  </style>
  <b>
    <slot name=title></slot>
  </b>
  <slot name=content></slot>
</template>

<my-element>
  <span slot="title">Hello World</span>
  <p slot="content">What a wonderful day!</p>
</my-element>
<my-element>
  <span slot="title">Hello Tomorrow</span>
  <p slot="content">What will you bring?</p>
</my-element>

JSFiddle:https ://jsfiddle.net/CustomElementsExamples/vu9w1zyx/

于 2020-04-09T14:28:22.763 回答