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

Vue 2插槽迁移Vue 3 v-slot语法的适配改造问题咨询

改造说明

首先你的现有代码存在一个prop名不匹配的问题:MyComponent 传给插槽的属性是 item,但父组件里取的是 slotProps.data,适配时要先修正这个不一致的问题,再按Vue3插槽规范调整写法。

第一步:调整MyComponent.vue代码

Vue3里<slot>的基础用法和Vue2完全一致,不需要改动,你只需要确保组件内正确声明了data属性即可,调整后完整代码如下:

<template>
  <div class="container">
    <!-- 给v-for加key是Vue3强制要求的规范,这里补充上 -->
    <template v-for="(item, index) in data" :key="index">
      <slot :item="item"></slot>
    </template>
  </div>
</template>

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

第二步:调整Parent.vue代码

Vue3里默认插槽的v-slot支持三种合法写法,可根据习惯选择:

写法1:保留原有全写(仅修正prop名匹配)

<MyComponent :data="你的业务数据源">
  <template v-slot="slotProps">
    <OtherComponent :data="slotProps.item"></OtherComponent>
  </template>
</MyComponent>

写法2:解构插槽Prop(Vue3更推荐的精简写法)

<MyComponent :data="你的业务数据源">
  <template v-slot="{ item }">
    <OtherComponent :data="item"></OtherComponent>
  </template>
</MyComponent>

写法3:用#缩写v-slot

默认插槽的标准名是default,所以可以缩写为#default:

<MyComponent :data="你的业务数据源">
  <template #default="{ item }">
    <OtherComponent :data="item"></OtherComponent>
  </template>
</MyComponent>

额外注意

如果你用到具名插槽,只需要把Vue2里slot="插槽名"的写法改成v-slot:插槽名或者#插槽名即可,子组件内<slot name="xxx">的用法不需要做任何改动。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 19:36:03