如何将数据从host元素传递给子元素

时间:2016-03-02 17:44:18

标签: polymer

无法让我的数据跨元素工作。假设我的主机元素中有一个对象“记录”。它可用于那个元素没问题。但是当我试图将视图分离成一个单独的元素时,它就不再有用了。

这是一段代码示例。 .template部分工作正常,但我无法复制子元素.my-list中的功能。当我尝试时,没有任何反应。

<dom-module id="host-element">
  ...
  <template is="dom-repeat" items="{{records}}">
      <p>{{item.userName}} - {{item.number}}</p>
    </template>

  <my-list></my-list>    

  <script>
    Polymer({
      is: 'host-element',
      ready: function() {
        this.records = [
          {userName: 'Bob'},
          {userName: 'Sally'}
        ];
      }
    });
  </script>

</dom-module>

如果我尝试简单地使用当前的.template代码并将其放入.my-list,它就不起作用。

我认为我需要将数据绑定到子元素,但我无法解决这个问题。在标记中添加:record =“{{records}}”,然后在子元素中使用它不起作用。

想象一下这很简单,只是在文档中找不到答案。

1 个答案:

答案 0 :(得分:3)

重要的是每个元素的顶级template都是普通模板(不是is="dom-repeat"或其他专业化),否则,它应该是直截了当的:

<link rel="import" href="//polygit.org/components/polymer/polymer.html">

<i>(Requires Chrome)</i>

<host-element></host-element>

<dom-module id="my-list">
  <template>
    <template is="dom-repeat" items="{{records}}">
      <p>{{item.userName}} - {{item.number}}</p>
    </template>
  </template>
  <script>
    Polymer({
      is: 'my-list'
    });
  </script>
</dom-module>

<dom-module id="host-element">
  <template>
    <my-list records="{{records}}"></my-list>
  </template>
  <script>
    Polymer({
      is: 'host-element',
      ready: function() {
        this.records = [{userName: 'Bob'}, {userName: 'Sally'}];
      }
    });
  </script>
</dom-module>

相关问题