Polymer 2.0 - “this.shadowRoot.querySelector”始终返回null

时间:2017-05-27 01:07:35

标签: javascript polymer web-component polymer-2.x

我想创建新元素并附加到#container上的connectedCallback部分。我使用this.shadowRoot.querySelector("#container")来选择元素,但它总是返回null。如何选择阴影根中的元素?

<!DOCTYPE html>
<html lang="en">

<head>
  <script src="https://polygit.org/components/webcomponentsjs/webcomponents-loader.js"></script>
  <link rel="import" href="https://polygit.org/components/polymer/polymer-element.html">
</head>

<body>
  <dom-module id="dom-element">

    <template>
        <div id="container">
          <p>I'm a DOM element. This is my shadow DOM!</p>
        </div>
      </template>

    <script>
      class DomElement extends Polymer.Element {
        connectedCallback() {
          this.attachShadow({
            mode: "open"
          })

          console.log(this.shadowRoot.querySelector("#container"))
        }

        static get is() {
          return "dom-element";
        }
      }
      customElements.define(DomElement.is, DomElement);
    </script>

  </dom-module>
  
  <dom-element></dom-element>
</body>

</html>

1 个答案:

答案 0 :(得分:4)

Polymer.Element已经附加了影子根,因此您不需要自己在connectedCallback()中执行此操作。更重要的是,您的自定义connectedCallback()必须致电super.connectedCallback()才能正常运营。看起来应该是这样的:

connectedCallback() {
  super.connectedCallback(); // DO THIS
  // this.attachShadow(...)  // DON'T DO THIS

  console.log('container', this.shadowRoot.querySelector("#container"));
}

demo