Polymer Multiple Iron-Collapse

非 Y 不嫁゛ 提交于 2019-12-12 03:38:02

问题


The polymer docs aren't clear on how to create a multiple toggle using iron-collapse. Is there an easy way to get each item to toggle? I had a look at multiple iron-collapse not working, expands only first but I could not get it to work. Maybe something has changed in polymer since then. Below is an example of the code I am using.

<div on-click="toggle"><paper-item><a class="paper-item-link"><strong>List Items</strong></a></paper-item></div>
<iron-collapse id="collapse">
<div>Content</div>
</iron-collapse>

<div on-click="toggle"><paper-item><a class="paper-item-link"><strong>List Items</strong></a></paper-item></div>
<iron-collapse id="collapse">
<div>Content</div>
</iron-collapse>

  toggle: function() {
    this.$.collapse.toggle();
  },

回答1:


Polymer's automatic node finding maps nodes by their IDs, but you have two nodes with the same ID, so only the last one encountered would be mapped to that ID (i.e., this.$.collapse refers to the second iron-collapse in your example). Also, since your click-handler refers to the same iron-collapse, both paper-items would toggle the same iron-collapse when clicked.

The quickest solution would be to use unique node IDs for each iron-collapse and to use unique click handlers:

<head>
  <base href="https://polygit.org/polymer+v1.9.2/components/">
  <script src="webcomponentsjs/webcomponents-lite.js"></script>
  <link rel="import" href="paper-item/paper-item.html">
  <link rel="import" href="iron-collapse/iron-collapse.html">
</head>
<body>
  <x-foo></x-foo>

  <dom-module id="x-foo">
    <template>
      <div on-click="toggle1">
        <paper-item>
          <a class="paper-item-link"><strong>List Items</strong></a>
        </paper-item>
      </div>
      <iron-collapse id="collapse1">
        <div>Content</div>
      </iron-collapse>

      <div on-click="toggle2">
        <paper-item>
          <a class="paper-item-link"><strong>List Items</strong></a>
        </paper-item>
      </div>
      <iron-collapse id="collapse2">
        <div>Content</div>
      </iron-collapse>
    </template>
    <script>
      HTMLImports.whenReady(function() {
        Polymer({
          is: 'x-foo',
          toggle1: function() {
            this.$.collapse1.toggle();
          },
          toggle2: function() {
            this.$.collapse2.toggle();
          }
        });
      });
    </script>
  </dom-module>
</body>

codepen



来源:https://stackoverflow.com/questions/37993857/polymer-multiple-iron-collapse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!