具有条件模板的聚合物获取元素

Polymer get element with conditional template

我的聚合物组件中有以下模板

<polymer-element name="my-element" attributes="show">
  <template if={{show}}>
     <select id="conditional-select">
     </select>
  </template>
<script>
Polymer({
    showChanged: function () {
        console.log(this.$['conditional-select']); //undefined
        setTimeout(function(){
           console.log(this.$['conditional-select']); //got it!
        },1000)
    }
})
</script>
</polymer-element>

为什么第一个控制台输出总是 undefined 显示改变了? 我明白,DOM 元素尚未在 showChanged 内呈现,但如何正确等待它?

看起来填充 this.$ 需要一点时间,所以 showChanged 中的更改对我有用

showChanged: function () {
    this.async(function() {
        console.log(this.$['conditional-select']); //undefined
        console.log(this.shadowRoot
            .querySelector('#conditional-select')); //got it!!                
    }.bind(this));
}