含义
简而言之,就是父组件提供的插槽内容(Click me)替换插槽出口(slot)
默认插槽
// FancyButton.vue
<button type="submit">
<!-- 插槽出口 -->
<slot>
Submit <!-- 默认内容:如果没有插槽内容Click me!,会渲染默认类容Submit -->
</slot>
</button>
// 父组件使用
<FancyButton>
Click me! <!-- 插槽内容 -->
</FancyButton>
具名插槽
// 父组件使用
<BaseLayout>
// v-slot:header的简写形式就是#header
<template #header>
<h1>Here might be a page title</h1>
</template>
// 默认插槽,#default不写也可以,会往没有name的slot插槽替换
<template #default>
<p>A paragraph for the main content.</p>
<p>And another one.</p>
</template>
<template #footer>
<p>Here's some contact info</p>
</template>
</BaseLayout>
// BaseLayout.vue
<div class="container">
<header>
<slot name="header"></slot>
</header>
<main>
<slot></slot>
</main>
<footer>
<slot name="footer"></slot>
</footer>
</div>
动态插槽
// dynamicSlotName可以是一个变量,动态的名称
<base-layout>
<template v-slot:[dynamicSlotName]>
...
</template>
<!-- 缩写为 -->
<template #[dynamicSlotName]>
...
</template>
</base-layout>
作用域插槽
插槽的内容无法访问到子组件的状态,如果需要访问子组件的数据就需要使用作用域插槽了。
<!-- <MyComponent> 的模板 -->
<div>
<slot :text="greetingMessage" :count="1"></slot>
</div>
<MyComponent v-slot="slotProps">
{{ slotProps.text }} {{ slotProps.count }}
</MyComponent>
// 也可以使用解构的方式
<MyComponent v-slot="{text, count}">
{{ text }} {{ count }}
</MyComponent>