学完这篇,你能把组件里"写死"的界面交出去,让调用方自己决定长什么样,同时还能反过来拿到子组件内部的数据——这正是具名插槽和作用域插槽要做的事。
第一步:先分清三种插槽
Vue 3 的插槽其实只有三类用法,先建立这个认知,后面的代码就不会混:
- 默认插槽:
<slot />,只有一个坑位,父组件直接写内容。
- 具名插槽:
<slot name="header" />,多个坑位各起一个名字。
- 作用域插槽:
<slot :item="item" />,子组件把内部数据"递"给父组件使用。
前两种解决"内容放哪儿",第三种解决"内容用什么数据渲染"。实际项目里,具名插槽和作用域插槽经常一起用。
第二步:具名插槽——给坑位起名字
新建 src/components/Panel.vue,在子组件里声明多个坑:
<template>
<div class="panel">
<header class="panel-hd">
<slot name="header">默认标题</slot>
</header>
<main class="panel-bd">
<slot /> <!-- 没写 name 就是默认插槽 -->
</main>
<footer class="panel-ft">
<slot name="footer" />
</footer>
</div>
</template>
父组件用 #名字 往对应坑位里填内容:
<Panel>
<template #header>
<h3>本月订单</h3>
</template>
<p>这里是正文,会进默认插槽。</p>
<template #footer>
<button>导出</button>
</template>
</Panel>
#header 是 v-slot:header 的简写,默认插槽写成 #default。
注意:v-slot 只能写在 <template> 标签或组件标签自身上。写成 <div #header> 会直接报错,这是新手最常见的一个红叉。
第三步:作用域插槽——把子组件的数据递出去
坑位里的内容虽然写在父组件,但经常需要子组件的数据。比如一个列表组件,它知道 item 是什么,父组件不知道。这时用作用域插槽,子组件在 <slot> 上挂属性,父组件用解构接收。
子组件 src/components/UserList.vue:
<script setup>
defineProps({ users: { type: Array, default: () => [] } })
</script>
<template>
<ul>
<li v-for="(user, index) in users" :key="user.id">
<!-- 把内部数据挂到 slot 上,父组件才能拿到 -->
<slot :user="user" :index="index">
{{ user.name }}
</slot>
</li>
</ul>
</template>
父组件接收:
<UserList :users="list">
<template #default="{ user, index }">
<span>{{ index + 1 }}. {{ user.name }}</span>
<em v-if="user.vip">VIP</em>
</template>
</UserList>
slot 上挂的所有属性会被打包成一个对象传给父组件,所以 { user, index } 的解构名字要和子组件挂的属性名一致。
注意:#default="{ user }" 里的大括号是解构,不是对象字面量。写成 #default="{ user }" 正确,写成 #default="user" 拿到的是整个 props 对象,得用 user.user 才能取到值。
第四步:具名 + 作用域组合(实战最常见形态)
封装一个表格组件,表头和每一行都开放给调用方,同时把行数据递出去。子组件 src/components/DataTable.vue:
<script setup>
defineProps({ rows: { type: Array, default: () => [] } })
</script>
<template>
<table>
<thead>
<tr><slot name="head" /></tr>
</thead>
<tbody>
<tr v-for="(row, i) in rows" :key="i">
<slot name="row" :row="row" :index="i" />
</tr>
</tbody>
</table>
</template>
父组件:
<DataTable :rows="orders">
<template #head>
<th>单号</th><th>金额</th><th>操作</th>
</template>
<template #row="{ row, index }">
<td>{{ row.no }}</td>
<td>{{ row.amount }}</td>
<td><a @click="remove(index)">删除</a></td>
</template>
</DataTable>
这样表格的"结构"由子组件负责,"每一格长什么样"由页面决定,复用性最好。
第五步:动态插槽名和默认内容
插槽名可以是变量,写法是 <template #[slotName]>:
<template #[dynamicName]>
<p>内容随变量切换</p>
</template>
<slot> 标签内部写的内容就是父组件没传时的兜底,比如 <slot name="footer"><button>取消</button></slot>。
第六步:用 $slots 判断有没有传
子组件里可以判断某个坑位是否被填充,用来决定要不要渲染外层容器:
<template>
<div class="wrap">
<div v-if="$slots.footer" class="ft">
<slot name="footer" />
</div>
</div>
</template>
注意:$slots 只在渲染时反映实际情况;父组件用了 v-if 时,$slots.footer 可能为 undefined,别写死基于它的复杂逻辑。
小结
- 具名插槽用
name 定义坑位,父组件用 #名字 填充,多个位置互不干扰。
- 作用域插槽在
<slot> 上挂属性传数据,父组件用 { } 解构接收。
- 具名 + 作用域组合是封装表格、列表、卡片这类组件的主流写法。
v-slot 只能写在 <template> 或组件标签上;解构写法别漏大括号。
<slot> 的内部内容就是默认兜底,配合 $slots 可以做条件渲染。