以编程方式在聚合物中设置数组项的属性值

Programmatically setting property value on array item in Polymer

本文关键字:数组 属性 设置 编程 方式 聚合物      更新时间:2023-09-26

我有一个使用聚合物的应用程序。在这个应用程序中,我有一个像这样的组件:

my-component.html

<dom-module id="view-tests">
    <template>
      <table>
        <tbody>
            <template is="dom-repeat" items="{{ items }}" as="item">              
              <tr>
                <td>[[ item.name ]]</td>
                <td><item-status status="[[ item.status ]]"></item-status></td>
              </tr>
            </template>
        </tbody>
      </table>
      <button on-click="bindClick">Bind</button>
    </template>
    <script>
        Polymer({
          is: "my-component",
          properties: {
            items: {
              type: Array,
              notify: true,
              value: function() {
                return [
                  new Item({ name:'Item 1', status:'In Stock' }),
                  new Item({ name:'Item 2', status:'Sold Out' })
                ];
              }  
            },
          },
          bindClick: function() {
            var items = items;              
            for (var i=0; i<items.length; i++) {
              if (i === 1) {
                items[i].status = 'In Stock';
              }
            }
          }          
        });
    </script>
</dom-module>
如上面的代码片段所示,还有另一个组件item-status

item-status.html

<dom-module id="test-status">
    <template>
        <span class$="{{ statusClass }}">{{ status }}</span>
    </template>
    <script>
        Polymer({
            is: "item-status",
            properties: {
                status: {
                    type: String,
                    value: '',
                    observer: '_statusChanged'
                }               
            },
            _statusChanged: function(newValue, oldValue) {
                if (newValue === 'In Stock') {
                  this.statusClass = 'green';
                } else if (newValue === 'Sold Out') {
                  this.statusClass = 'red';
                } else {
                  this.statusClass = 'black';
                }
            }
        });
  </script> 
</dom-module>

初始数据绑定工作正常。然而,当我点击"绑定"按钮时,文本并没有像我期望的那样更新。另外,文字的颜色也没有像我想象的那样变化。我故意有var items = items;,因为在我的实际代码中,有一个回调发生,我必须将项目传递到回调。我不确定是否有更好的方法。然而,我的观点并没有正确地更新。

感谢您提供的任何帮助

  1. 当我点击"绑定"按钮时,文本不会像我期望的那样更新

要使其工作,您必须使用this.set('item.1 ')。status', 'In Stock')。有关数组绑定的详细信息,请参阅https://www.polymer-project.org/1.0/docs/devguide/data-binding.html#array-binding。

  • 另外,文字的颜色并没有像我期望的那样改变。
  • 你只是在设置类。你必须为项目设计样式。在item-status中包含样式标签,如下所示

    <style>
          .red {
            color: red;
          }
          .green {
            color: green;
          }
    </style> 
    

    3。var items = items;故意的,因为在我的实际代码中,有一个回调发生了

    我不认为你可以在回调中为数组项设置值,并使聚合物观察者工作。如果你在你的场景上发布更多的细节,有人可能会帮助你。

  • 这是一个很好的做法,让你的dom模块id和你的聚合物'is' id相同。这是我第一次遇到不同的id,我几乎肯定它会破坏一些东西。
  • 工作jsbin: http://jsbin.com/yugofo/edit?html,console,output