聚合物在点击时更改纸质图标按钮中的图标

Polymer change the icon in paper-icon-button onclick

本文关键字:图标 按钮 聚合物      更新时间:2023-09-26

使用聚合物 1.0

我正在尝试在单击时更改纸质图标按钮的(聚合物)图标。无法让它工作。

到目前为止,我已经这样做了。

<paper-icon-button class="expandComments"  
 icon="{{isCollapsed? 'expand-more' : 'expand-less'}}" on-click="expanding">
</paper-icon-button>
"

扩展更多"和"扩展更少"是我想使用的图标。

创建的功能:

created: function() {
  this.isCollapsed = true;
},

扩展功能:

 expanding: function() {
  var content = this.$.review_item_content;
  if(content.classList.contains('review-item-content')) {
    this.isCollapsed = false;
    content.classList.remove('review-item-content');
  }else{
    this.isCollapsed = true;
    content.classList.add('review-item-content');
  }
},

它到达扩展函数并更改 isCollapsed 的值并删除样式类。

现在我也尝试了这个:

<paper-icon-button class="expandComments" icon="{{expandIcon}}" on-click="expanding"></paper-icon-button>

icon: {
  expandIcon: 'expand-more',
},
created: function() {
this.isCollapsed = true;
},
expanding: function() {
  var content = this.$.review_item_content;  
  if(content.classList.contains('review-item-content')) {
    this.icon.expandIcon = 'expand-less';
    this.isCollapsed = false;
    content.classList.remove('review-item-content');
  }else{
    this.icon.expandIcon = 'expand-more';
    this.isCollapsed = true;
    content.classList.add('review-item-content');
  }
},

x ? y : z 这样的表达式在 Polymer 1.0 中(尚)不受支持

需要改用计算绑定,如下所示:

icon="{{_icon(isCollapsed)}}"

Polymer({
 properties: {
   isCollapsed: {
     type: Boolean,
     value: true
   }
 },
  _icon: function (isCollapsed) {
    return isCollapsed ? 'icon1' : 'icon2'
  }
});

更改 isCollapsed 的值将自动重新评估函数并相应地设置图标值。

编辑:由于只要未定义isCollapsed就不会调用_icon,因此您必须使用默认值对其进行初始化(请参阅上面编辑的代码中的properties对象)。

在Scarygami发布解决方案后,仍然存在问题。 isCollapsed 仍然未定义,即使它是在创建中设置的,因此图标图像在启动时没有加载。

解决方案:聚合物全局变量

 <paper-icon-button class="expandComments" icon="{{_icon(isCollapsed)}}" on-click="expanding"></paper-icon-button>
<script>
(function() {
 var isCollapsed = true;
 Polymer({
  is: 'edit-review',
  properties: {
  reviews: Object
  },
  _icon: function (isCollapsed) {
  return isCollapsed ? 'expand-more' : 'expand-less';
  },
  ready: function() {
   this.isCollapsed = isCollapsed;
  },
  expanding: function() {
   var content = this.$.review_item_content;
   if(content.classList.contains('review-item-content')) {
    this.isCollapsed = false;
    }else{
    this.isCollapsed = true;
   }
  },
});
})();
</script>