外观
插槽实质
Vue 组件的内容都是通过渲染函数产生,无论是使用 <template> 模板还是手写渲染函数。
插槽的实质是一个函数,函数参数为父组件传入的模板内容,函数的返回值为 <slot> 渲染的结果。
如图,render 函数返回的虚拟 DOM 是 <template> 的内容,<slot> 要渲染的内容通过 renderSlot 函数产生。

具名插槽
当有多个插槽时,需要使用 name 属性为各个 <slot> 命名用以区分。
父组件中使用包含 v-slot 指令的 <template> 元素,并将插槽的名称传给给指令,v-slot 可简写为 #,所以 v-slot:header 简写为 #header。
注意插槽名是作为指令参数(v-slot:header)而不是值(v-slot="header"❌)。
vue
<template>
<BaseLayout>
<template #header></template>
<template #default></template>
<template #footer></template>
</BaseLayout>
</template>默认插槽 name 属性值为 default,或者不写 name 属性,插槽名称会作为参数传给 renderSlot 函数。
vue
<template>
<div class="container">
<header>
<slot name="header"></slot>
</header>
<main>
<slot></slot>
</main>
<footer>
<slot name="footer"></slot>
</footer>
</div>
</template>ts
const __sfc__ = {}
import {
renderSlot,
createElementVNode,
openBlock,
createElementBlock
} from 'vue'
const _hoisted_1 = { class: 'container' }
function render(_ctx, _cache, $props, $setup, $data, $options) {
return (_openBlock(), _createElementBlock('div', _hoisted_1, [
createElementVNode('header', null, [
renderSlot(_ctx.$slots, 'header')
]),
createElementVNode('main', null, [
renderSlot(_ctx.$slots, 'default')
]),
createElementVNode('footer', null, [
renderSlot(_ctx.$slots, 'footer')
])
]))
}
__sfc__.render = render
__sfc__.__file = 'src/BaseLayout.vue'
export default __sfc__当一个组件同时接收默认插槽和具名插槽时,所有位于顶级的非 <template> 节点都被隐式地视为默认插槽的内容。
条件插槽
结合 $slots 属性与 v-if 来决定插槽是否显示。
vue
<template>
<div class="container">
<div v-if="$slots.header" class="header">
<slot name="header" />
</div>
</div>
</template>动态插槽名
插槽名称可为变量,这样可实现动态渲染。
vue
<template>
<BaseLayout>
<template v-slot:[dynmaicSlotName]></template>
<template #[dynamicSlotName]></template>
</BaseLayout>
</template>作用域插槽
作用域插槽就是 v-slot 带值的插槽,父组件中,插槽内容无法访问子组件的数据,作用域插槽会向 <slot> 组件传递 props,然后 props 作为 v-slot 指令的值,这样在父组件中就能访问到子组件的数据。
vue
<template>
<BaseLayout>
<template v-slot="slotProps">{{ slotProps.text }}</template>
</BaseLayout>
</template>给 <slot> 传递 props。
vue
<template>
<div class="container">
<slot text="hello" :count="1"></slot>
</div>
</template>js
const __sfc__ = {}
import {
renderSlot,
openBlock,
createElementBlock
} from 'vue'
function render(_ctx, _cache, $props, $setup, $data, $options) {
return (openBlock(), createElementBlock('div',
{ class: 'container' },
[renderSlot(_ctx.$slots, 'default', {
text: 'hello',
count: 1
})
]))
}
__sfc__.render = render
export default __sfc__