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

如何用dom-repeat复用插槽内容?插槽内容仅重复一次的问题求助

解决Polymer列表组件插槽内容仅重复一次的问题

嘿,我之前也遇到过一模一样的问题!当你在dom-repeat的模板里直接用<slot>的时候,会发现插槽里的内容只显示一次,根本不会跟着列表项重复。这是因为插槽的内容来自父组件的Light DOM,dom-repeat只是在重复<slot>这个元素本身,但插槽本身只会渲染一次父组件传进来的内容,自然就达不到我们要的复用效果啦。

下面给你两种靠谱的解决办法:

方法一:克隆插槽内容到内部模板

这种方法适配Polymer 1.x和2.x,核心思路是把父组件通过插槽传进来的行内容,克隆到组件内部的dom-template里,让dom-repeat去重复渲染这个克隆后的模板。

组件代码

<dom-module id="list-repeater">
  <template>
    <template is="dom-repeat" items="{{items}}">
      <!-- 用dom-template绑定每个item的数据 -->
      <template is="dom-template" id="rowTemplate" bind="{{item}}"></template>
    </template>
  </template>
  <script>
    Polymer({
      is: 'list-repeater',
      properties: {
        items: {
          type: Array,
          value: () => []
        }
      },
      ready() {
        // 获取插槽里的有效元素内容(过滤掉文本节点)
        const slotElements = this.querySelector('slot')
          .assignedNodes({flatten: true})
          .filter(node => node.nodeType === Node.ELEMENT_NODE);
        
        if (slotElements.length > 0) {
          // 把插槽内容克隆到内部模板里
          this.$.rowTemplate.content.appendChild(slotElements[0].cloneNode(true));
        }
      }
    });
  </script>
</dom-module>

使用组件的方式

<list-repeater items='[{"name": "Item 1"}, {"name": "Item 2"}, {"name": "Item 3"}]'>
  <!-- 这里就是你要复用的行模板啦 -->
  <div>
    <paper-button>[[item.name]]</paper-button>
  </div>
</list-repeater>

方法二:直接传入模板作为插槽(更简洁)

如果用的是Polymer 2+,可以直接把模板作为插槽内容传进去,组件内部拿到模板引用后,传给dom-repeat的template属性,这样dom-repeat就会直接用这个模板渲染每一行,非常直观。

组件代码

<dom-module id="list-repeater">
  <template>
    <!-- 专门用一个命名插槽来接收行模板 -->
    <slot name="row-template"></slot>
    <!-- 把拿到的模板传给dom-repeat -->
    <template is="dom-repeat" items="{{items}}" template="[[rowTemplate]]"></template>
  </template>
  <script>
    Polymer({
      is: 'list-repeater',
      properties: {
        items: {type: Array, value: () => []},
        rowTemplate: {type: Object}
      },
      ready() {
        // 获取命名插槽里的模板元素
        this.rowTemplate = this.querySelector('[slot="row-template"]');
      }
    });
  </script>
</dom-module>

使用组件的方式

<list-repeater items='[{"name": "Item 1"}, {"name": "Item 2"}]'>
  <!-- 用命名插槽传入你的行模板 -->
  <template slot="row-template">
    <paper-button>[[item.name]]</paper-button>
  </template>
</list-repeater>

这两种方法都能完美解决插槽内容只重复一次的问题,你可以根据自己用的Polymer版本选合适的~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:52:44