在 Vue.js 中,插槽 (slot) 是一种用于在组件之间共享 HTML 内容的机制。通过在父组件中定义插槽,并在子组件中使用 <slot>
标签接收插槽内容,实现更加灵活和可复用的组件。
以下是一个示例,演示如何在 Vue.js 中使用插槽:
<!-- 父组件 -->
<template>
<div>
<child-component>
<p>Hello, world!</p>
</child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
}
}
</script>
<!-- 子组件 -->
<template>
<div>
<h1>My Component</h1>
<slot></slot> // 默认插槽
</div>
</template>
<script>
export default {
name: 'ChildComponent'
}
</script>
在这个示例中,父组件使用 <child-component>
标签来渲染子组件,并在标签内部定义了一个 <p>
标签。在子组件中,使用 <slot>
标签来定义插槽,并将插槽内容渲染出来。当父组件渲染子组件时,插槽内容将被插入到 <slot>
标签所在的位置,从而实现了动态渲染 HTML 内容的效果。
具名插槽
与普通插槽相比,它允许在父组件中定义多个插槽,并在子组件中使用不同的名称接收插槽内容,从而实现更加灵活和可复用的组件。
以下是一个示例,演示如何在 Vue.js 中使用具名插槽:
<!-- 父组件 -->
<template>
<div>
<child-component>
<template v-slot:header> // 指定插槽名
<h1>Hello, world!</h1>
</template>
<template v-slot:content>
<p>This is the content.</p>
</template>
</child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
}
}
</script>
<!-- 子组件 -->
<template>
<div>
<slot name="header"></slot>
<slot name="content"></slot>
</div>
</template>
<script>
export default {
name: 'ChildComponent'
}
</script>
在这个示例中,父组件使用 <child-component>
标签来渲染子组件,并在标签内部定义了两个具名插槽分别为 header
和 content
。在子组件中,使用 <slot>
标签并设置 name
属性来定义具名插槽,并将插槽内容渲染出来。当父组件渲染子组件时,header
插槽的内容将被插入到 <slot>
标签 name="header"
所在的位置,content
插槽的内容将被插入到 <slot>
标签 name="content"
所在的位置,从而实现了动态渲染 HTML 内容的效果。
除了使用 v-slot
指令来定义具名插槽之外,还可以使用 slot
元素的 name
属性来定义具名插槽,例如:
<!-- 父组件 -->
<template>
<div>
<child-component>
<template #header>
<h1>Hello, world!</h1>
</template>
<template #content>
<p>This is the content.</p>
</template>
</child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
}
}
</script>
<!-- 子组件 -->
<template>
<div>
<slot name="header"></slot>
<slot name="content"></slot>
</div>
</template>
<script>
export default {
name: 'ChildComponent'
}
</script>
在这个示例中,使用 #
符号来缩写 v-slot
,并使用 slot
元素的 name
属性来定义具名插槽。
需要注意的是,使用具名插槽时,插槽内容必须使用 <template>
标签来包含,而不是直接使用 HTML 标签。这是因为具名插槽允许您在父组件中使用多个插槽,并通过名称来区分它们,因此需要使用 <template>
标签来包含插槽内容,并使用 v-slot
或 #
来指定插槽名称。