2017-10-15 131 views
0

我正在玩聚合物2.0,我不明白如何將對象作爲元素屬性傳遞。將對象傳遞給聚合物2中的元素屬性

這裏是我的代碼:

<dom-module id="notes-app"> 
    <template> 
    <style> 
     :host { 
     display: block; 
     } 
    </style> 
    <button on-click="loadNotes">Get the notes</button> 
    <template is="dom-repeat" items="[[notes]]" as="note"> 
    <note recipe='JSON.stringify(note)'></note> 
    </template> 
</template> 
<script> 
    class NotesApp extends Polymer.Element { 
    static get is() { return 'notes-app'; } 
    static get properties() { 
     return { 
     notes: { 
      type: Array, 
      value: [] 
     } 
     }; 
    } 
    loadNotes() { 
     this.notes = [ 
     {"desc":"desc1", "author":"auth1", "type":"type1"}, 
     {"desc":"desc2", "author":"auth2", "type":"type2"}, 
     {"desc":"desc3", "author":"auth3", "type":"type3"} 
     ]; 
    } 
    } 
    window.customElements.define(NotesApp.is, NotesApp); 
</script> 
</dom-module> 

simple-note是誰擁有Object類型的屬性的元素:

<dom-module id="note"> 
    <template> 
    <style> 
     :host { 
     display: block; 
     } 
    </style> 
    <div> 
     <fieldset> 
     <label>description</label>{{note.desc}}<br> 
     <label>author</label>{{note.author}}<br> 
     <label>type</label>{{note.type}} 
     </fieldset> 
    </div> 
    </template> 
    <script> 
    class SimpleNote extends Polymer.Element { 
     static get is() { return 'simple-note' } 
     static get properties() { 
     return { 
      note: { 
      type: Object, 
      value: {}, 
      notify: true 
      } 
     }; 
     } 
    } 
    customElements.define(SimpleNote.is, SimpleNote); 
    </script> 
</dom-module> 

正如你可以看到我想要note-app在其notes屬性顯示的所有對象通過將代表音符的對象傳遞給每個simple-note元素(不知道它是否是使元素互相交互的正確方法)。當我按下notes-app按鈕時,我希望它發生。在這種情況下,如何將對象傳遞給元素屬性?

回答

0

由於您試圖將該變量作爲object傳遞,您應該使用屬性綁定而不是屬性綁定(僅支持字符串)。

  • Polymer data bindings需要捲曲或方括號({{twoWayBinding}}[[oneWayBinding]])。例如,設置<x-child>元素的note值的foo財產,模板會是這個樣子:

    <template is="dom-repeat" items="[[notes]]" as="note"> 
        <x-child foo="[[note]]"> 
    </template> 
    
  • 鑑於SimpleNote.is等於"simple-note",我假設你的<note>使用和<dom-module id="note">只在你的問題中輸入錯字。它們應設置爲simple-note,作爲元素名稱must start with a lowercase ASCII letter and must contain a dash

  • 它看起來像你綁定recipe屬性,但<simple-note>聲明瞭一個note屬性(無recipe),並結合在它的模板note子屬性。我認爲recipe是另一個錯字。

working demo

+0

我的壞。我會檢查我的例子,並儘快更新我的問題。看不到你的代碼示例