Vue.js 报错:The slot “xxx“ is not defined
·
Vue.js 报错:The slot “xxx” is not defined —— 3 分钟急救手册
当你在控制台看到:
[Vue warn]: The slot "xxx" is not defined.
Vue 在告诉你:
“父组件给了一个具名插槽 #xxx,但子组件里没有 <slot name="xxx"> 来接。”
按「一看二对三兜底」三步法,3 分钟定位 + 解决。
一、一看:确认报错场景
| 使用方式 | 示例 |
|---|---|
| 父组件 | <template #footer> 或 v-slot:footer |
| 子组件 | <slot name="footer"> 接收 |
二、二对:名字必须完全一致
1️⃣ 大小写/拼写错误
<!-- 父组件 ❌ -->
<template #footer>
<p>底部内容</p>
</template>
<!-- 子组件 ❌ -->
<slot name="Footer"> <!-- 大小写不一致 -->
</slot>
修复:保持大小写一致
<slot name="footer"> <!-- ✅ -->
</slot>
2️⃣ 命名空间(模块化)遗漏
// 子组件模块
export default {
name: 'MyCard',
slots: ['header', 'footer'] // ✅ 显式声明(Vue3 文档)
}
3️⃣ 动态插槽名拼错
<!-- 父组件 -->
<template #[dynamicSlot]>
<p>内容</p>
</template>
// ❌ dynamicSlot = 'foot' 但子组件只有 'footer'
修复:对齐变量值
const dynamicSlot = 'footer' // ✅
三、三兜底:可选插槽与默认值
1️⃣ 可选插槽:允许不存在
<!-- 子组件:提供后备内容 -->
<slot name="footer">
<p>默认底部</p>
</slot>
2️⃣ 父组件不传时不报错
<!-- 父组件:不传 #footer 即可 -->
<MyCard>只有默认内容</MyCard>
四、一键排查脚本(浏览器控制台)
// 打印子组件所有已定义 slot 名称
console.log(
[...document.querySelectorAll('my-card')].map(el =>
el.__vue_parent_component?.slots
)
)
五、一句话总结
“slot 未定义” = 父组件
#xxx与子组件<slot name="xxx">名字没对齐。
对好大小写、补缺失、提供默认值,警告立刻消失。
最后问候亲爱的朋友们,并邀请你们阅读我的全新著作

更多推荐
所有评论(0)