【问题标题】:dom-repeat not reflecting data changesdom-repeat 不反映数据更改
【发布时间】:2017-12-22 05:57:05
【问题描述】:

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

查看

<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 = ''
     }
    });
}

目标是单击“selection”中的项目获取其 id 值并将其与“subSelection”中具有相同 id 的项目匹配,然后将活动值更改为“活动”或“”。

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

【问题讨论】:

    标签: javascript polymer


    【解决方案1】:

    所以我最终通过 this.set(property, value) 解决了它。聚合物在如何实现这一点方面也非常特别。但以下在我的更新功能中起作用:

    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", '');
           }
       );
     }
    

    【讨论】:

    • 这就是它在 Polymer 中的工作方式。如果不使用 mutator 函数set/push,库就不可能知道哪些变量发生了变化。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多