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

如何访问插槽内使用的组件的插槽props?Vue作用域插槽传值问题

实现方案

1. 最简实现:作用域插槽批量透传

你不需要在父组件编写子项的内部逻辑,只需要把List组件暴露的插槽参数批量透传给指定的子项组件即可:

Home组件代码调整

<list 
  class="mapkeyList"
  :content="displayList"
  :filterbar="true"
  @handleSelection="addSelection"
  @delete="deleteElement"
  @editItem="editItem"
  header="Mapkeys"
  :key="mapkeyListKey"
>
  <!-- 接收List暴露的所有插槽参数 -->
  <template #default="slotProps">
    <!-- 批量透传属性和事件给ListItem,无需逐个声明 -->
    <list-item v-bind="slotProps" v-on="slotProps" />
  </template>
</list>

Options组件使用时,仅需要把<list-item>替换为<list-options-item>即可,其他代码无需改动。

ListItem组件调整

在子项组件中声明需要用到的属性即可,未用到的参数无需处理,事件emit后会自动透传回List组件:

<template>
  <div class= "flexSpaceBetween" @click="$emit('auswahl',item)">
    <div class="textFett">
      {{item[0]}}
    </div>
    <div>
      {{item[1]}}
    </div>
  </div>
</template>
<script>
export default {
  props: {
    // 按需声明用到的属性即可
    item: {
      type: Array,
      required: true
    },
    index: Number,
    dragable: Boolean
  }
}
</script>

2. 优化方案:动态组件封装(适合后续新增多类子项)

如果后续子项类型持续增加,可以给List组件新增一个组件类型参数,直接在List内部渲染对应子项,父组件无需写插槽代码:

List组件新增prop

props: {
  // 原有prop保持不变,新增子项组件参数
  itemComponent: {
    type: [Object, String],
    required: true
  }
}

List模板调整

把原有插槽替换为动态组件,原有属性和事件绑定保持不变:

<div v-for=" (item, index) in showedContent" :key="index">
  <component 
    :is="itemComponent"
    :item="item"
    :index="index"
    :dragable="dragableItems"
    @auswahl="auswahlHandle"
    @deleteElement="deleteElement"
    @editItem="editItem"
    :dontShowButtons="dontShowButtons"
    @dragStart="handleOverDragStart"
    :dragItem="dragItem"
    @position="$emit('emitPosition',item)"
    :deaktivierbar="deaktivierbar"
  />
</div>

父组件调用简化

<!-- Home组件调用 -->
<list 
  class="mapkeyList"
  :content="displayList"
  :filterbar="true"
  @handleSelection="addSelection"
  @delete="deleteElement"
  @editItem="editItem"
  header="Mapkeys"
  :key="mapkeyListKey"
  :item-component="ListItem"
/>

<!-- Options组件调用 -->
<list 
  <!-- 其他配置保持不变 -->
  :item-component="ListOptionsItem"
/>

后续新增子项组件时,仅需要编写对应子项的逻辑,父组件传入新的组件参数即可,无需修改List组件代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 22:54:00