在 Vue3 中,插槽(Slots)的使用方式与 Vue2 中基本相同,但有一些细微的差异。以下是在 Vue3 中使用插槽的示例:
// 堆代码 duidaima.com
// ChildComponent.vue
<template>
<div>
<h2>Child Component</h2>
<slot></slot>
</div>
</template>
// ParentComponent.vue
<template>
<div>
<h1>Parent Component</h1>
<ChildComponent>
<p>This is the content of the slot.</p>
</ChildComponent>
</div>
</template>
<script>
import { defineComponent } from 'vue'
import ChildComponent from './ChildComponent.vue'
export default defineComponent({
name: 'ParentComponent',
components: {
ChildComponent
}
})
</script>
在上面的示例中,ChildComponent 组件定义了一个默认插槽,使用 <slot></slot> 标签来表示插槽的位置。在 ParentComponent 组件中,使用 <ChildComponent> 标签包裹了一段内容 <p>This is the content of the slot.</p>,这段内容将被插入到 ChildComponent 组件的插槽位置。需要注意的是,在 Vue3 中,默认插槽不再具有具名插槽的概念。如果需要使用具名插槽,可以使用 v-slot 指令。以下是一个示例:
// ChildComponent.vue
<template>
<div>
<h2>Child Component</h2>
<slot name="header"></slot>
<slot></slot>
<slot name="footer"></slot>
</div>
</template>
// ParentComponent.vue
<template>
<div>
<h1>Parent Component</h1>
<ChildComponent>
<template v-slot:header>
<h3>This is the header slot</h3>
</template>
<p>This is the content of the default slot.</p>
<template v-slot:footer>
<p>This is the footer slot</p>
</template>
</ChildComponent>
</div>
</template>
<script>
import { defineComponent } from 'vue'
import ChildComponent from './ChildComponent.vue'
export default defineComponent({
name: 'ParentComponent',
components: {
ChildComponent
}
})
</script>
在上面的示例中,ChildComponent 组件定义了三个插槽,分别是名为 header、默认插槽和名为 footer 的插槽。在 ParentComponent 组件中,使用 <template v-slot:header> 来定义 header 插槽的内容,使用 <template v-slot:footer> 来定义 footer 插槽的内容。默认插槽可以直接写在组件标签内部。
需要注意的是,在 Vue3 中,v-slot 只能用在 <template> 标签上,不能用在普通的 HTML 标签上。如果要在普通 HTML 标签上使用插槽,可以使用 v-slot 的缩写语法 #。例如,<template v-slot:header> 可以简写为 #header。