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

Vue3:如何让父组件传入的插槽组件接收孙组件的props?

解决Vue插槽深层透传props的问题

要让RowComponent获取到孙组件传递的data和idx,核心是使用作用域插槽语法,让父组件接收孙组件暴露的插槽props,再传递给RowComponent。具体修改如下:

1. 父组件修改

父组件需要通过v-slot(可简写为#)接收插槽传递的props,再绑定到RowComponent上:

// Parent
<Child :array="this.data">
  <template v-slot="{ data, idx }">
    <RowComponent :data="data" :idx="idx" />
  </template>
</Child>

这里的{ data, idx }是解构孙组件通过<slot>暴露的props,直接将这些props绑定给RowComponent即可。

2. 子组件无需改动

子组件仅需透传插槽内容,不需要处理props,保持原有代码即可:

// Child
<template #detailed>
  <GrandChild :data="this.data">
    <slot></slot>
  </GrandChild>
</template>

3. 孙组件保持现有逻辑

孙组件通过:data="item"和:idx="index"把循环项和索引暴露给插槽的逻辑无需修改:

// Grandchild
<template>
  <div
    v-for="(item, index) in data"
    :key="index"
  >
    <slot :data="item" :idx="index"></slot>
  </div>
</template>

原理说明

  • 孙组件的<slot>绑定的属性会成为作用域插槽的props,向上传递到父组件的插槽定义中。
  • 父组件必须显式通过v-slot接收这些props,才能将其传递给内部的RowComponent。如果直接写<RowComponent/>,相当于没有接收和传递这些作用域props,组件自然拿不到对应的值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 00:55:14