【问题标题】:Pushing to data-bound array used in dom-repeat (Polymer)推送到 dom-repeat (Polymer) 中使用的数据绑定数组
【发布时间】:2016-11-16 02:14:24
【问题描述】:

我在自定义 Polymer 元素中有一个数据绑定数组 (dom-repeat),我需要将新数据推送到数组中。它不显示项目,即使它知道已添加 2 个元素。我在这里错过了什么?

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>

【问题讨论】:

    标签: javascript data-binding polymer dom-repeat


    【解决方案1】:

    将项目推入数组时使用 Polymer 的 array mutation methods

    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

    【讨论】:

    • 你能看看这个other example吗?即使我使用 Polymer 数组突变方法更新了示例代码,使用带有计算属性的 "hidden$=" 似乎也没有触发。感谢您的帮助。
    • 不确定绑定不更新的原因。如果你只想在people[] 为空时隐藏,你可以这样做:hidden$="[[!people.length]]" jsfiddle.net/nf7ncbsn/1
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多