在 Vue3 中,使用 slot
可以为一个组件定义一个插槽,可以使用该插槽插入其他组件或HTML标签。
定义插槽:
在组件中使用 <slot>
标签定义插槽,可以使用 name
属性来命名插槽。例如:
<template>
<div>
<h1><slot name="title">默认标题</slot></h1>
<p><slot name="content">默认内容</slot></p>
</div>
</template>
在上面的代码中,我们定义了两个插槽,分别以 title
和 content
命名,如果没有传递具体内容到插槽中,则插入默认值。
使用插槽:
在使用组件时,可以使用 v-slot
或 #
来绑定插槽。例如:
<template>
<div>
<my-component>
<template #title>自定义标题</template>
<template #content>自定义内容</template>
</my-component>
</div>
</template>
在上面的代码中,我们将自定义的标题和内容插入到了组件 my-component
的对应插槽中。
除了具名插槽,Vue3 还支持默认插槽,可以简写为 #default
或直接使用 <slot>
标签。
<template>
<div>
<my-component>
自定义默认内容
</my-component>
</div>
</template>
上面的代码中,我们直接将内容插入了组件 my-component
的默认插槽中。