如何迭代通过一个数组的对象在聚合物

How to iterate through an array of objects in polymer

本文关键字:数组 一个 对象 聚合物 何迭代 迭代      更新时间:2023-09-26

所以我可以很容易地遍历数组或列表。

<template is="dom-repeat" items="{{inputs}}">
    <paper-input label={{item}} id={{item}} style="width:5em"></paper-   input>
</template>

然而,我在迭代对象数组时遇到了问题。

<iron-data-table id="outputtable" items="{{output}}">
        <template is="dom-repeat" items="[[output]]">
                <data-table-column name="[[item.key]]">
                    <template>[[item.value]]</template>
                </data-table-column>
        </template>
</iron-data-table>          

这段代码可能不正确,但我无法越过错误

Polymer::Attributes: cannot decode Array as JSON

我迭代字符串数组的第一个例子,我实际上想迭代对象数组,但没有做到。

[{"uri":"/emoji/1"},{"uri":"/emoji/2"}]

对象数组的简单例子。

<iron-ajax id="ajaxPost" url={{url}} handle-as="json" content-type="application/json" method="POST" on-response=clearAndOutput > </iron-ajax>

this.output [Object { uri="/emoji/1"}, Object { uri="/emoji/2"}, Object { uri="/emoji/3"}, 35 more...] 
clearAndOutput: function(data) {
    this.returnvalue = data.detail.response;
}

dom-repeat中,items数组的每个数组元素都可以被重复器模板中的item访问(尽管您可以选择不同的迭代器名称)。如果名为"output"的数组包含"uri"属性,则可以在模板中像这样迭代该数组:

<template is="dom-repeat" items="[[output]]">
  <div>[[item.uri]]</div>
</template>

HTMLImports.whenReady(() => {
  Polymer({
    is: 'x-foo',
    properties: {
      output: {
        type: Array,
        value: () => [{"uri":"/emoji/1"},{"uri":"/emoji/2"}]
      }
    }
  });
});
<head>
  <base href="https://polygit.org/polymer+1.7.0/components/">
  <script src="webcomponentsjs/webcomponents-lite.min.js"></script>
  <link rel="import" href="polymer/polymer.html">
</head>
<body>
  <x-foo></x-foo>
  <dom-module id="x-foo">
    <template>
      <template is="dom-repeat" items="[[output]]">
        <div>[[item.uri]]</div>
      </template>
    </template>
  </dom-module>
</body>

codepen

您看到的错误表明"output"实际上不是一个数组,因此您必须调试它(或提供有关如何设置它以帮助解决问题的其他信息)。