Polymer 更改纸图标按钮 onclick 中的图标

Polymer change the icon in paper-icon-button onclick

使用聚合物 1.0

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

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

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

'expand-more 'expand-less'是我想用的图标。

创建函数:

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 的值并删除样式 class。

现在我也尝试了这个:

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

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

您将需要使用计算绑定,例如:

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


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

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

编辑:由于 _icon 不会被调用,只要 isCollapsed 未定义,您将不得不使用默认值初始化它(参见 properties 中的对象编辑上面的代码)。

经过Scarygami贴出的解决方案,还是有问题。 isCollapsed 仍然未定义,即使它已在创建时设置,因此图标图像未在启动时加载。

解决方案:Polymer global variables

 <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>