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

Vue 3 如何在多级组件间传递具名插槽

Vue3多级子组件间传递具名插槽的解决方案

问题描述

在Vue 3.2.45项目中复用带有自定义单元格的大型表格组件时,希望将不同的单元格组件传入表格组件,但不清楚如何在多级子组件间传递具名插槽。期望在App.vue中使用名为cell的具名插槽的slotProps,实现类似test插槽传递id参数的效果。

现有代码示例

App.vue

<script setup lang="ts">
import { ref } from 'vue'
import { ITable } from './types.ts'
import Table from './Table.vue'

const table = ref<ITable>({
  tree: [
    { data: [{ value: '0' }, { value: '1' }, { value: '2' }, { value: '3' }] },
    { data: [{ value: '0' }, { value: '1' }, { value: '2' }, { value: '3' }] },
  ],
})
</script>

<template>
  <Table :table="table">
    <template #cell="{ cell }">
      Hello {{ cell.value }}
    </template>
    <template #test="{ id }">
      <div class="row">Row above is {{ id }}</div>
    </template>
  </Table>
</template>

Table.vue

<template>
  <div class="table">
    <template v-for="(row, rowI) in table.tree" :key="rowI">
      <Row :row="row" />
      <slot name="test" :id="rowI" />
    </template>
  </div>
</template>

Row.vue

<template>
  <div class="row">
    <div class="cell" v-for="(cell, cellI) in row.data" :key="cellI">
      <slot name="cell" :cell="cell" />
    </div>
  </div>
</template>

解决方案

问题核心是中间组件Table.vue没有将App.vue中定义的cell插槽透传给Row.vue,导致Row.vue无法访问到这个插槽内容。只需修改Table.vue,将cell插槽转发给Row组件即可:

修改后的Table.vue

<template>
  <div class="table">
    <template v-for="(row, rowI) in table.tree" :key="rowI">
      <Row :row="row">
        <!-- 转发cell插槽,并传递所有slotProps -->
        <template #cell="slotProps">
          <slot name="cell" v-bind="slotProps" />
        </template>
      </Row>
      <slot name="test" :id="rowI" />
    </template>
  </div>
</template>

简化写法(Vue3.2+支持)

可以使用Vue3的插槽透传语法进一步简化代码:

<template>
  <div class="table">
    <template v-for="(row, rowI) in table.tree" :key="rowI">
      <!-- 直接透传cell插槽给Row组件 -->
      <Row :row="row" #cell="slotProps">
        <slot name="cell" v-bind="slotProps" />
      </Row>
      <slot name="test" :id="rowI" />
    </template>
  </div>
</template>

效果验证

修改完成后,App.vue中的#cell插槽将能正确接收Row.vue传递的cell参数,页面会显示Hello 0、Hello 1等内容,实现和test插槽一致的参数传递效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 02:45:18