如何将对象推入数组 - Polymer 2.x.

问题描述 投票:0回答:1

我正在尝试将项目推送到Polymer中的数组。 this.requestdom-repeat模板中,它在DOM中正确显示。但是,当我记录this.request时,它显示最后一个条目覆盖了所有以前的条目。

例如,如果我推动1,2,3,4作为描述,dom-repeat将是准确的,但当我记录this.request它显示4,4,4,4

<ul id="products">
  <template is="dom-repeat" items="[[request]]" restamp="true">
    <li>
      <p>[[item.description]]</p>
    </li>
  </template>
</ul>

...

request: {
  type: Object,  
  value: []
},

productData: {
  type:Object,
  value: {}  
}

...

addItemToList() {
  this.push('request', this.productData);
}

尝试使用this.set解决方法不会产生DOM更新,并且数组索引仍会被覆盖。

addItemToList() {
  let i = 'request.' + this.request.length;
  this.set(i, this.productData)
}

问题似乎是由于推送对象而不是字符串,可以将对象作为数组索引推送吗?

可以使用什么方法来保持这些同步?

arrays push polymer-2.x
1个回答
0
投票

您可以按照描述将对象推送到数组中。我无法理解你是如何制作productData的,但我试图举例说明如下:

Demo

addItemToList() {
  this.productData = {description:this.request.length}
  this.push('request', this.productData);
    console.log(this.request)  
}

您可以在演示链接中查看更详细的代码。

© www.soinside.com 2019 - 2024. All rights reserved.