一、定义
插槽就是子组件提供一个占位符,指定父组件传递的内容在子组件具体哪个地方渲染。<slot>
元素是一个插槽出口,标示了父元素提供的插槽内容将在哪里被渲染。插槽内容可以是文本、元素甚至组件。(一句话总结就是:子组件提供位置,父组件提示内容)。
二、匿名插槽
匿名插槽指的是父组件中未指定名称的插槽,匿名插槽最多只能有一个。匿名插槽适用于只插入一个内容的时候。
父组件中
<ChildComponent>
<p>hello world</p>
<button>点击提交</button>
</ChildComponent>
子组件ChildComponent中
<div class="child">
<slot></slot>
</div>
子组件渲染出的 DOM是:
<div class="child">
<p>hello world</p>
<button>点击提交</button>
</div>
三、具名插槽
具名插槽指父组件向子组件传递特定名称的内容,子组件可以选择性地使用这些内容。
父组件通过<template>
中的v-slot
指令将内容传递给子组件。v-slot 可以简写成 #,子组件可以使用<slot>
元素来定义具名插槽的位置,并在需要时插入具名插槽的内容。具名slot 可清晰的插入多个slot。
父组件中
<ChildComponent>
<template #title>
<h2>我是歌手2024</h2>
</template>
<template #message>
<div>你给歌手投票了吗?</div>
</template>
</ChildComponent>
子组件中
<div class="child">
<div>
<slot name="title"></slot>
</div>
<div>
<slot name="message"></slot>
</div>
</div>
子组件渲染出的 DOM是:
<div class="child">
<div>
<h2>我是歌手2024</h2>
</div>
<div>
<div>你给歌手投票了吗?</div>
</div>
</div>