uniapp小程序循环插槽如何使用

在uniapp开发小程序时,如何使用循环插槽?我在组件中定义了插槽,但循环渲染时无法正确显示数据,不知道该如何在v-for中配合插槽使用。求具体的代码示例和实现方法。

2 回复

在uniapp小程序中,使用循环插槽需要结合v-forslot

示例:

<!-- 父组件 -->
<child-comp>
  <template v-slot:default="slotProps">
    <view>{{ slotProps.item }}</view>
  </template>
</child-comp>

<!-- 子组件 -->
<view v-for="(item, index) in list">
  <slot :item="item"></slot>
</view>

关键点:

  1. 子组件用v-for循环
  2. 通过:item="item"传递数据
  3. 父组件用v-slot:default="slotProps"接收数据

在 UniApp 中,循环插槽通常用于在自定义组件中结合 v-for 循环渲染插槽内容,实现动态数据与灵活内容结构的结合。以下是使用方法:

1. 自定义组件(子组件)

在子组件中,使用 slot 并绑定循环数据,通过 v-for 遍历数据,并为每个项提供插槽。

<!-- 子组件 child.vue -->
<template>
  <view>
    <view v-for="(item, index) in list" :key="index">
      <!-- 使用具名插槽,传递当前项数据到插槽 -->
      <slot name="item" :item="item" :index="index"></slot>
    </view>
  </view>
</template>

<script>
export default {
  props: {
    list: {
      type: Array,
      default: () => []
    }
  }
}
</script>

2. 父组件使用

在父组件中,通过 v-slot 指令接收子组件传递的数据,并定义每个循环项的插槽内容。

<!-- 父组件 parent.vue -->
<template>
  <view>
    <child :list="dataList">
      <!-- 使用 v-slot 接收子组件传递的 item 和 index -->
      <template v-slot:item="slotProps">
        <view class="item">
          {{ slotProps.item.name }} - 索引: {{ slotProps.index }}
        </view>
      </template>
    </child>
  </view>
</template>

<script>
import child from '@/components/child.vue'

export default {
  components: { child },
  data() {
    return {
      dataList: [
        { name: '项目1' },
        { name: '项目2' },
        { name: '项目3' }
      ]
    }
  }
}
</script>

<style>
.item {
  padding: 10px;
  border-bottom: 1px solid #eee;
}
</style>

关键点说明:

  • 子组件:通过 v-for 循环 list 数据,每个循环项内使用 <slot>,并通过 :item="item" 传递数据。
  • 父组件:使用 <template v-slot:item="slotProps"> 接收数据,slotProps 包含子组件传递的 itemindex
  • 支持默认插槽或具名插槽,根据需求调整 name 属性。

应用场景:

适用于列表渲染,但每个项的内容结构需要自定义的情况,如动态表单、卡片列表等。

回到顶部