2017-10-15 85 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

我的坏。我会检查我的例子,并尽快更新我的问题。看不到你的代码示例