在 Vue.js 中,<slot>
是用于在父组件中传递内容到子组件的一种机制。它允许你在父组件中定义一些内容,并在子组件中使用 <slot>
标签来插入这些内容,从而实现父子组件之间的内容传递和复用。
1.匿名插槽
使用 <slot> 插槽接收父组件传递的内容
父组件
<template>
<div>
<h1>父组件</h1>
<p>这是父组件的内容。</p>
<ChildComponent></ChildComponent>
</div>
</template>
子组件
<template>
<div>
<h2>子组件</h2>
<!-- 使用 <slot> 插槽接收父组件传递的内容 -->
<slot></slot>
</div>
</template>
2.具名插槽
通过 <slot>
标签的 name
属性来区分不同的插槽
父组件
<template>
<div>
<h1>父组件</h1>
<!-- 使用命名插槽传递内容 -->
<ChildComponent>
<template v-slot:title>
&l