Vue 中的插槽(slot)是一种灵活的方式,用于在组件中传递内容,允许开发者将父组件的内容插入到子组件中的指定位置。下面是一个简单的示例,演示了 Vue 中插槽的使用:
假设我们有一个名为 Card
的组件,它是一个通用的卡片组件,可以显示标题和内容。我们希望这个组件在使用时可以灵活地插入任意的标题和内容。
<!-- Card.vue -->
<template>
<div class="card">
<h2>{{ title }}</h2>
<!-- 这里是插槽的位置 -->
<slot></slot>
</div>
</template>
<script>
export default {
props: {
title: {
type: String,
required: true
}
}
};
</script>
<style>
.card {
border: 1px solid #ccc;
padding: 20px;
margin: 10px;
}
</style>
在父组件中,我们可以使用 Card
组件,并在其中放置任意的内容作为插槽的内容。
<!-- ParentComponent.vue -->
<template>
<div>
<Card title="My Card">
<!-- 这里是插槽的内容 -->
<p>This is the content of my card.</p>
</Card>
</div>
</template>
<script>
import Card from './Card.vue';
export default {
components: {
Card
}
};
</script>
在这个例子中,Card
组件定义了一个插槽,插槽的位置由 <slot></slot>
表示。在父组件 ParentComponent.vue
中使用 Card
组件时,我们可以将任意的内容放置在 Card
组件中,这些内容会被自动插入到 Card
组件中的插槽位置。
这种方式使得 Card
组件非常灵活,可以根据不同的使用场景来展示不同的内容,而不需要修改 Card
组件的代码。这就是 Vue 中插槽的基本使用方式。