dom-repeat不反映数据变化

时间:2017-12-21 20:59:02

标签: javascript polymer

我尝试了计算属性和其他各种技术,但视图并未反映我的模型。模型更新,但视图不更新。

查看

<div class="selection">
  <ul>
   <template is="dom-repeat" items="{{state.selection}}">
    <li>
     <a data-selection$="{{item.id}}" on-click="selection">{{item.name}}</a>
    </li>
   </template>
  </ul>
</div>

<div class="selection sub-selection">
 <template is="dom-repeat" items="{{state.subSelection}}">
  <ul id$="subselection-{{item.id}}" class$="[[item.active]]">
   <template is="dom-repeat" items="{{item.selections}}">
      <li>
       <a data-selection="{{item.id}}" on-click="selection">{{item.name}}</a>
      </li>
   </template>
  </ul>
 </template>
</div>

模型

constructor(){
   super()
   this.state = {
       selection: [
          {
            id: 1,
            name: 'Selection One'
           },
           {
            id: 2,
            name: 'Selection Two'
           }
        ],

    subSelection: [
          {
            id: 1,
            name: 'Sub Selection One',
            active: 'active'
           },
           {
            id: 2,
            name: 'Sub Selection Two',
            active: ''
           }
        ]
  }

  selection(event){
    event.preventDefault();
    let self = this;
    let id = parseInt(event.currentTarget.getAttribute('data-selection'));

    self.state.subSelection.forEach(function(key, index){
     if(key.id === id){
       key.active = 'active'
     }else{
       key.active = ''
     }
    });
}

目标是点击“选择”中的项目获取其ID值,并将其与“subSelection”中的项目匹配,并使用相同的ID,然后将活动值更改为“active”或“”。

除了视图更新外,一切顺利。

1 个答案:

答案 0 :(得分:1)

所以我最终通过this.set(属性,值)来解决它。聚合物在如何实现这一点方面非常特别。但是以下工作在我的更新功能中:

selection(event){
   event.preventDefault();
   let self = this;
   let id = parseInt(event.currentTarget.getAttribute('data-selection'));      
   self.state.subSelection.forEach(function(key, index){
       if(key.id === id){
         self.set("state.subSelection."+index+".active", 'active');
       }else{
         self.set("state.subSelection."+index+".active", '');
       }
   );
 }