如何在 Polymer 中显示来自父对象的信息?

How to display information from a parent object in Polymer?

我正在编写一个从 API 收集信息的 Polymer 元素,它应该根据结果的对象键将其分发给子元素。

my-parent 元素执行 ajax 调用。如果在 response() 函数中获取响应。

我的问题是:如何以某种方式存储接收到的信息,以便我可以将其分发并显示给子元素?

App.html

<my-parent collector="1">
    <h1>The Results</h1>
    <h3><my-child name="title"><!-- should output FOO --></my-child></h3>
    <h3><my-child name="description"><!-- should output BAR --></my-child></h3>
</my-parent>

我的-parent.html

<dom-module id="my-parent">
  <template>
    <style>
      :host {
        display: block;
      }
    </style>
    <content></content>
    <iron-ajax auto url="//someurl/posts/[[collector]]" handle-as="json" last-response="{{response}}" on-response="onResponse" id="xhr"></iron-ajax>
 </template>
  <script>
      Polymer({
        is: 'my-parent',
        properties: {
          collector: {
            type: String,
            notify: true
          },
          response: {
            type: String
          }
        },
        onResponse: function(response){
          /* WHAT TO DO HERE? */
        }
      })
  </script>
</dom-module>

API 结果来自 //someurl/posts/1

{
   "title": "FOO",
   "description": "BAR"
}

我的-child.html

<dom-module id="my-child">
  <template>
    <style>
      :host {
        display: block;
      }
    </style>
    {{itemes}}
  </template>
  <script>
      Polymer({
        is: 'my-child',
        properties: {
          itemes: {
            type: String,
            value: function(){
              return "what to do here?";
            }
          }
        },
        key: {
            type: String,
            notify: true
          }
      })
  </script>
</dom-module>

因为 <my-child> 实际上是 <my-parent> 的光 DOM 子节点,而不是 <my-parent> 的局部 DOM 的一部分(即阴影 DOM), 你必须使用 Polymer's DOM API.

在 my-parent.html 中,从 <iron-ajax> 中删除 on-response="onResponse" 属性,并将 <script> 更新为以下内容:

Polymer({
  is: 'my-parent',
  properties: {
    collector: {
      type: String,
      notify: true
    },
    response: {
      type: Object,
      observer: '_handleResponse'
    }
  },
  _handleResponse: function(response) {
    Polymer.dom(this).querySelector('[name="title"]').itemes = response.title;
    Polymer.dom(this).querySelector('[name="description"]').itemes = response.description;
  }
})

然后my-child.html的<script>可以更新为:

Polymer({
  is: 'my-child',
  properties: {
    itemes: {
      type: String
    }
  }
})

虽然这可能不是您想要的,但它向您展示了如何将数据从父组件传输到它的 DOM 子组件。在此示例中,我们设置每个 <my-child>itemes 属性 并且 属性 设置为将其文本值呈现为本地 DOM 文本节点.

综上所述,我不确定这种方法是否适用于 Shadow DOM v1 规范(您可能需要让节点成为其直接子节点,然后可能将其作为light DOM child 或 local/shadow DOM child),但是对于使用 Shady DOM 的 Polymer 1.x,它就可以了。