具名插槽是Vue实现多区域内容分发的核心方式,子组件通过<slot name="xxx">定义命名出口,父组件用v-slot:xxx或#xxx精准投递内容,并支持作用域插槽传递数据及内置默认内容提升健壮性。

具名插槽是 Vue 实现多区域内容分发的核心方式,关键在于子组件定义带 name 的 <slot>,父组件用 v-slot:xxx(或简写 #xxx)精准投递内容。
子组件:定义多个命名出口
在子组件模板中,按业务区域逻辑命名插槽,比如 header、left、center、right、footer 等。每个 <slot name="xxx"></slot> 是一个独立接收点:
-
<slot name="header"></slot>—— 用于顶部标题栏 -
<slot name="left"></slot>—— 放 Logo 或系统名称 -
<slot name="center"></slot>—— 承载导航、搜索或面包屑 -
<slot name="right"></slot>—— 显示用户头像、操作按钮等 - 不加 name 的
<slot></slot>是默认插槽,仅一个,接收未匹配的匿名内容
父组件:用 v-slot 精准绑定内容
必须显式使用 v-slot:xxx 或缩写 #xxx,名称要与子组件中 name 完全一致(包括大小写和拼写):
使用 `@ainative/vue-sdk` 为 Vue 3 应用添加 AI 聊天功能。适用于以下场景:(1) 安装 `@ainative/vue-sdk`,(2) 在 Vue 组件中使用 `useChat` 组合式函数,(3) 提供……
<template #header><h1>后台管理</h1></template><template #left><img src="logo.png" /></template><template #right><el-button @click="logout">退出</el-button></template>- 没传某个插槽时,该位置显示其内部默认内容(如占位图或空 div),不影响其他区域
- 多个
<template #xxx>块顺序无关,Vue 按 name 自动归位
结合作用域数据,支持动态定制
如果需要把子组件内部状态暴露给父组件渲染,可在插槽上绑定属性:
立即学习“前端免费学习笔记(深入)”;
- 子组件:
<slot name="right" :user="currentUser" :hasPermission="canEdit"></slot> - 父组件:
<template #right="{ user, hasPermission }">{{ user.name }}<el-button v-if="hasPermission">编辑</el-button></template> - 这样权限判断、样式控制等交由业务层决定,Header 结构保持高度复用
提供合理默认内容,提升健壮性
每个具名插槽内可内置基础实现,防止父组件遗漏传入导致界面异常:
<slot name="left"><span>我的系统</span></slot><slot name="right"><button @click="handleLogout">退出</button></slot>- 这些默认内容只在父组件未提供对应
#xxx时生效,不影响定制覆盖 - Vue 3 中
slot和slot-scope已废弃,统一使用v-slot

















