2017-01-16 93 views
0

更好的辦法我有以下元素:通過綁定到子元素聚合物1.0

<link rel="import" href="../my-control/my-control.html" /> 

<dom-module id="my-page"> 
    <template> 
     <!-- pass the value down to the children element --> 
     <my-control my-property="{{myProperty}}"></my-control> 
    </template> 

    <script> 
     Polymer({ 
     is: 'my-page', 

     properties: { 
      myProperty: { 
       type: String, 
       value: '', 
       reflectToAttribute: true 
      } 
     } 
     }); 
    </script> 
</dom-module> 

這是「孩子」控制

<dom-module id="my-control"> 
    <template> 
     <!-- print the value of the property --> 
     <span>{{myProperty}}></span> 
    </template> 

    <script> 
     Polymer({ 
     is: 'my-control', 

     properties: { 
      myProperty: { 
       type: String, 
       value: '', 
       reflectToAttribute: true 
      } 
     } 
     }); 
    </script> 
</dom-module> 

這是我如何使用它。我這樣做是因爲實際上"my-page"並不真的需要一個屬性,但是"my-control"可以,它包含在"my-page"的DOM中。有沒有其他辦法可以做到這一點?因爲我傳遞了一個模型,而且我必須按屬性爲每個屬性反序列化它?

<link rel="import" href="/my-page/my-page.html" /> 

<!-- declare parent element and value --> 
<my-page my-property="ABCDE-12345"></my-page> 
+1

不是。我能想到的唯一方法是在js select'my-page'訪問它的'shadow dom'(方法在V0和V1規範中有所不同),然後選擇'my-control'並賦值。 – a1626

+0

我希望像Angular這樣的「父」數據綁定語法有,但我加倍檢查,我沒有找到任何有關聚合物1.x文檔 – Raffaeu

+1

聚合物 – a1626

回答

-1

你的問題表達了爲了通過給孩子傳遞屬性重新聲明父一子屬性的關注。實際上,如果父項完全未使用父項(除非父項的用戶需要在該屬性上進行雙向數據綁定),則無需在父項中重新聲明屬性。

以下是聲明性示例,在父項中省略了屬性重新聲明

<dom-module id="x-foo"> 
    <template> 
    <my-page foo="123"></my-page> 
    </template> 
    <script> 
    Polymer({is: 'x-foo'}); 
    </script> 
</dom-module> 

<dom-module id="my-page"> 
    <template> 
    <my-element foo="[[foo]]"></my-element> 
    </template> 
    <script> 
    // no property declaration needed for one-way binding 
    Polymer({is: 'my-page'}); 
    </script> 
</dom-module> 

codepen

旁註:你不需要設置reflectToAttribute數據綁定。

+0

沒有什麼但這正是我在做什麼... – Raffaeu

+0

@Raffaeu我承認它*看起來*非常類似於你已經在做的事情,但它不完全一樣。你的問題表達了對不必要地在家長中聲明財產的擔憂,我的回答表明,如果你只是直接傳遞給孩子,那麼實際上並不需要這樣做。我添加了一個部分來表明父代中的重新聲明只會用於雙向綁定,並且可能會使問題變得模糊,因爲很明顯,您根本不需要父項(或父母的用戶)。我會更新我的答案,至少澄清一點。 – tony19