Pushing to data-bound array used in dom-repeat (Polymer)

爷,独闯天下 提交于 2019-12-02 12:03:23

问题


I have a data-bound array (dom-repeat) in a custom Polymer element, and I need to push new data into the array. It's not displaying the items, even though it knows 2 elements have been added. What am I missing here?

jsFiddle

<link rel="import" href="../../bower_components/polymer/polymer.html">

<dom-module id="main-element">
<template>
    <ul>
        <template is="dom-repeat" items="{{people}}">
            <li>{{item.first}}</li>
        </template>
    </ul>
</template>

<script>
    (function() {
        'use strict';
        Polymer({
            is: 'main-element',
            properties: {
                people: {
                    type: Array,
                    value: function() {
                        return [];
                    }
                }
            },
            ready: function() {
                // Mock data retrieval
                this.people.push({"first": "Jane", "last": "Doe"});
                this.people.push({"first": "Bob", "last": "Smith"});
            }
        });
    })();
</script>


回答1:


Use Polymer's array mutation methods when pushing items into the array:

this.push('people', {"first": "Jane", "last": "Doe"});
this.push('people', {"first": "Bob", "last": "Smith"});

<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>
  <main-element></main-element>

  <dom-module id="main-element">
    <template>
      <ul>
        <template is="dom-repeat" items="{{people}}">
          <li>{{item.first}}</li>
        </template>
      </ul>
    </template>

    <script>
      HTMLImports.whenReady(function() {
        'use strict';
        Polymer({
          is: 'main-element',
          properties: {
            people: {
              type: Array,
              value: function() {
               return [];
              }
            }
          },
          ready: function() {
            // Mock data retrieval
            this.push('people', {"first": "Jane", "last": "Doe"});
            this.push('people', {"first": "Bob", "last": "Smith"});
          }
        });
      });
    </script>
  </dom-module>
</body>

codepen



来源:https://stackoverflow.com/questions/40622982/pushing-to-data-bound-array-used-in-dom-repeat-polymer

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