聚合物:this。$ [elementId]未定义

Yai*_*pro 4 polymer

这是一个简单的聚合物元素,只需使用其id和访问内部元素this.$.[elementId],然后对其进行记录。运行此简单代码,您将能够看到返回的element undefined。为什么?

<dom-module id="custom-element">
  <template>
          <template is="dom-if" if="[[condition]]">
             <div id="main"></div>
          </template>
  </template>

  <script>
    class CustomElement extends Polymer.Element {
      static get is() { return "custom-element"; }
            static get properties() {
                return {
                   condition : Boolean
                };
            }

            ready(){
                super.ready();
                console.log(this.$.main); // logs "undefined"
            }
    }

    customElements.define(CustomElement.is, CustomElement);
  </script>

</dom-module>
Run Code Online (Sandbox Code Playgroud)

Yai*_*pro 7

聚合物this.$仅引用本地DOM中未动态添加的元素。因此,放置在其中的元素dom-ifdom-repeat模板不会添加到this.$object

如果您想选择动态元素,则需要进入dom并使用类似 this.shadowRoot.querySelector('#main')


这是摆脱这个问题的解决方案。在您的中添加以下代码ready()

if (this.$)
    this.$ = new Proxy(this.$, {
        get: ($, id) => $[id] || this.shadowRoot.getElementById(id),
        set: ($, id, element) => {
            $[id] = element;
            return true;
        }
    });
Run Code Online (Sandbox Code Playgroud)