我可以在开槽内容上使用dom-repeat将每个开槽子项包装在某个标签内吗?

时间:2018-04-29 12:52:49

标签: polymer polymer-2.x dom-repeat

我想使用dom-repeat将一堆子节点包装在<li>个标签中。问题是,我想重复的节点是自定义元素,通过插槽插入,似乎dom-repeat只接受通过属性传递的数据。

我想做的是:

<dom-module id="my-custom-element">
  <template>
    <section>
      ...
      <ul>
        <dom-repeat items="{{ TOP-LEVEL NODES IN LIST SLOT }}">
          <template>
            <li>{{ item }}</li>
          </template>
        </dom-repeat>
      </ul>
    </section>
  </template>
</dom-module>

使用它:

<my-custom-element>
  <ul slot="LIST">
    <my-other-custom-element></my-other-custom-element>
    <my-other-custom-element></my-other-custom-element>
    <my-other-custom-element></my-other-custom-element>
  </ul>
</my-custom-element>

1 个答案:

答案 0 :(得分:1)

我不认为这是最好的 Polymer 方式,但它有效:

  <x-foo>
    <ul slot="list">
      <div> hi </div>
      <div> hello </div>
      <div> bye </div>
    </ul>
  </x-foo>

  <dom-module id="x-foo">
    <template>
      <h2> The raw slotted items </h2>
      <slot name="list" id="list"></slot>
        <h2> The slotted list items wrapped with 'li' </h2>
      <ul id="styledList"></ul>
    </template>
  </dom-module>

这是诀窍:

 class XFoo extends Polymer.Element {
    static get is() { return 'x-foo'; }

    static get properties() {
      return {
        items: {
          type: Array,
          value: function() {
            return [1, 2, 3, 4]
          }
        }
      };
    }

    connectedCallback() {
      super.connectedCallback();
      this.$.list.addEventListener('slotchange', (e) => this.bindSlottedItems() );
    }

    bindSlottedItems() {
        let items = this.$.list.assignedNodes({flatten: true})[0].childNodes;
        items = [].slice.call(items)
        this.$.styledList.innerHTML = items.filter((item) => item.outerHTML).map((item) => {
          return `<li> ${item.outerHTML} </li>`
        }).join('');
    }
  }
  customElements.define(XFoo.is, XFoo);

https://codepen.io/MWalid/pen/aGJRWy