dom-repeat template fails to render array with error 'expected array for items'

心不动则不痛 提交于 2020-01-03 12:59:30

问题


I have a simple template that renders an array object. However, it fails with the following message:

[dom-repeat::dom-repeat]: expected array for `items`, found [{"code":1,"name":"Item #1"},{"code":2,"name":"Item #2"},{"code":3,"name":"Item #3"}]

The array is passed in the attribute of the custom element in the following format:

[{"code":1,"name":"Item #1"},{"code":2,"name":"Item #2"},{"code":3,"name":"Item #3"}]

I have read the docs on template repeaters several times and still unable to find what I am doing wrong.

Any help would be much appreciated!

Here is my custom element:

<dom-module id="x-myelement">   
    <template>
        <div>
            <h1>{{title}}</h1>
            <ul>
                <template is="dom-repeat" as="menuitem" items="{{items}}">
                    <li><span>{{menuitem.code}}</span></li>
                </template>
            </ul>           
        </div>
    </template>
    <script>
        (function() {
            Polymer({
              is: 'x-myelement',

              title: String,

              items: {
                  type: Array,
                  notify: true,
                  value: function(){ return []; }
              }           
            });
          })();
    </script>
</dom-module>

And here is now I use it:

<x-myelement title="Hello Polymer" 
             items='[{"code":1,"name":"Item #1"},{"code":2,"name":"Item #2"},{"code":3,"name":"Item #3"}]'>
</x-myelement>

回答1:


You need to put your element properties into the properties object (see the Polymer documentation on properties):

Polymer({
  is: 'x-myelement',
  properties: {
    title: String,
    items: {
      type: Array,
      notify: true,
      value: function() {return [];}
    }
  }
});

Otherwise Polymer has no information about your properties. It treated items as a string and didn't parse the attribute value as a JSON array. Eventually dom-repeat was passed a string for its items property as well, resulting in the error that you saw.



来源:https://stackoverflow.com/questions/31908958/dom-repeat-template-fails-to-render-array-with-error-expected-array-for-items

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!