2017-03-09 90 views
1

我通過聚合物2.0玩弄Web組件。聚合物2.0並將屬性傳遞給兒童

結束HTML我想寫這個樣子的:

<card size="small"> 
    <card-header> 
    // Markup 
    </card-header> 
    <card-body> 
    // Markup 
    </card-body> 
    <card-footer> 
    // Markup 
    </card-footer> 
</card> 

正如你所看到的,我通過尺寸爲頂級組件。我打算聆聽這些卡的寬度,並減少標題,正文和頁腳上的填充項,當它們達到較小尺寸時,基本上是響應元素。

我不知道該怎麼做是將大小的屬性值傳遞給card-header,card-bodycard-footer聚合物聲明。

這裏是我如何定義card

<link rel="import" href="card-header.html"> 
    <dom-module id="card"> 
     <template> 
     <style> 
      // Style things 
     </style> 

     <slot></slot> 
     </template> 
     <script> 
    Polymer({ 
     is: 'card', 

     properties: { 
     size: { 
      type: String, 
      value: "medium", 
      observer: '_observeSize' 
     }, 
     }, 

     _observeSize: function() { 
     const sizes = { 
      tiny: "1em", 
      small: "2em", 
      medium: "3em", 
      large: "6em" 
     }; 

     if (this.size == "tiny") { 
      this.customStyle['--padding-x'] = sizes.tiny; 
      this.customStyle['--padding-y'] = sizes.tiny; 
     } else if (this.size == "small") { 
      this.customStyle['--padding-x'] = sizes.small; 
      this.customStyle['--padding-y'] = sizes.small; 
     } else if (this.size == "medium") { 
      this.customStyle['--padding-x'] = sizes.medium; 
      this.customStyle['--padding-y'] = sizes.medium; 
     } else if (this.size == "large") { 
      this.customStyle['--padding-x'] = sizes.large; 
      this.customStyle['--padding-y'] = sizes.large; 
     } else { 
      this.customStyle['--padding-x'] = sizes.medium; 
      this.customStyle['--padding-y'] = sizes.medium; 
     } 

     this.updateStyles(); 
     }, 

     _responsiveObserver: function() { 
     // Update this.size based on width of this element. 
     } 

    }); 
    </script> 
</dom-module> 

而這裏的我是如何定義card-header

<dom-module id="card-header"> 
    <template> 
     <style> 
     // Style 
     </style> 
    <slot></slot> 

    </template> 

    <script> 
    Polymer({ 
     is: 'card-header', 

     properties: { 
     size: { 
      type: String, 
     } 
     }, 

     ready: function() { 
     console.log(this.size); 
     // console.log(hostValue::size); ???? something like this ???? 
     } 
    }); 
    </script> 
</dom-module> 

TL; DR:我如何獲得父節點的屬性值,或將值傳遞給特定子節點(card-headercard-bodycard-footer),而不更新聚合物DOM中的屬性?

+0

超感興趣的是這是一個私人物業,通過卡_responsiveObserver私人方法,如果可能的話?! –

回答

1

解決方案

有解決這幾個方面,但我意識到我把我需要的<slot></slot>什麼,所以我可以在卡級別做填充的邏輯,然後在CSS變量處理。

_observeSize: function() { 
    // const and if else blocks still exist, untouched. Since they set the customStyle object on this element... 

    var children = this.querySelectorAll('card-header, card-body, card-footer'); 

    children.forEach(function (child) { 
     child.style = this.customStyle; 
    }); 

    this.updateStyles(); 
    }, 
相關問題