You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Polymer 1.X中dom-if不生效问题求助

解决Polymer 1.X中dom-if不随对象子属性变化更新的问题

嘿,这个坑我当初用Polymer 1.x的时候也踩过!问题出在你更新requirement.allLoaded的方式上——Polymer 1.x的属性绑定系统默认只会监听整个对象引用的变化,而不是对象内部子属性的修改。你直接改this.requirement.allLoaded,Polymer根本没察觉到这个属性路径的变化,所以dom-if模板自然不会更新。

给你两个靠谱的解决方案:

方案1:使用Polymer内置的set方法(推荐)

Polymer专门提供了set()方法来处理嵌套属性的更新,它会主动通知框架属性路径发生了变化,触发绑定更新。修改你的测试函数:

_testButton: function(){
  console.log(this.requirement);
  // 用属性路径语法更新子属性
  this.set('requirement.allLoaded', !this.requirement.allLoaded);
}

方案2:重新赋值整个对象

如果需要一次性修改多个子属性,你可以创建一个新的对象替换原来的requirement,这样对象引用变了,Polymer会检测到并更新绑定:

_testButton: function(){
  console.log(this.requirement);
  // 用Object.assign创建新对象,保留原有属性,更新指定字段
  this.requirement = Object.assign({}, this.requirement, {
    allLoaded: !this.requirement.allLoaded
  });
}

另外提醒一下,如果你后续需要监听requirement.allLoaded的变化,可以给属性添加一个观察者:

properties: {
  requirement: { 
    type: Object, 
    value: () => ({ allLoaded: false, tagsLoaded: false }),
    observer: '_requirementChanged'
  }
},
_requirementChanged: function(newVal) {
  console.log('allLoaded状态变化:', newVal.allLoaded);
}

这样修改后,点击测试按钮切换allLoaded状态,dom-if就能正常显示/隐藏内容啦!

内容的提问来源于stack exchange,提问作者NeitoFR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:02:15