数据更改时元素未更新

element not updated when data changes

我有一个 vaadin-checkbox:

<vaadin-checkbox id=[[item.id]] disabled="true" checked="[[item.checked]]">[[item.description]]</vaadin-checkbox>

我定义了属性:

static get properties() {
    return {
        items: {
            type: Array,
            notify: true,
            value: function() {
                return [];
            }
        }
    };
}

当我现在按某个按钮更改数据时:

_selectItem(event) {
    const item = event.model.item;

    if (item.checked === true) {
        this.$.grid.deselectItem(item);
    } else {
        this.$.grid.selectItem(item);
    }

    item.checked = !item.checked;
}

复选框的状态仍然是checked="true"。为什么复选框没有更新?当我更改项目的描述时,同样的事情:

_selectItem(event) {
    event.model.item.description = 'test';
}

test 描述从未出现。复选框永远不会更新。

按钮单击处理程序未更新复选框的原因在于 Polymer 2 数据系统。 Polymer 没有检测到变化,也没有相应地更新模板。

为了以 Polymer 可以检测到的方式进行更改,您有两个选择:

  • 如果您可以可靠地假设 dom-repeat 使用的 index 始终与 items 数组中该元素的索引相匹配,则使用 this.set(`items.${event.model.index}.checked`, !item.checked)(如果不是这种情况您使用 dom-repeat 的排序或过滤功能)。在此处查看示例 https://jsfiddle.net/vlukashov/epd0dn2j/
  • 如果不知道更新项在items数组中的索引,也可以使用Polymer.MutableData mixin and notify Polymer that something has changed inside the items array without specifying the index of the changed item. This is done by calling this.notifyPath('items') after making a change. However, this requires that your element extends the Polymer.MutableData mixin, and that dom-repeat has the mutable-data attribute set. See an example here: https://jsfiddle.net/vlukashov/epd0dn2j/24/

Polymer 2 docs 中有更多相关信息。