在 Vue.js 中,slot
用于分发内容,类似于将内容插入到模板中的占位符。在子组件中定义的 slot
可以在父组件中被填充。通过这种方式,你可以复用一个组件模板,但在不同的使用场景中插入不同的内容。
让我们来看一个简单的示例:
<!-- ChildComponent.vue -->
<template>
<div>
<slot></slot>
</div>
</template>
<!-- ParentComponent.vue -->
<template>
<ChildComponent>
<p>这段内容将被插入到 ChildComponent 中的 slot 中。</p>
</ChildComponent>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
}
};
</script>
在这个示例中,<ChildComponent>
中的 <slot>
标签被 <ParentComponent>
中的 <p>
标签替换。
你也可以在子组件中定义多个命名的 slot,并在父组件中指定哪些内容应该插入到哪个 slot。这对于更复杂的布局特别有用。例如:
<!-- ChildComponent.vue -->
<template>
<div>
<header>
<slot name="header"></slot>
</header>
<main>
<slot></slot>
</main>
<footer>
<slot name="footer"></slot>
</footer>
</div>
</template>
<!-- ParentComponent.vue -->
<template>
<ChildComponent>
<template v-slot:header>
<h1>这是标题</h1>
</template>
<p>这是一些主要内容。</p>
<template v-slot:footer>
<p>这是页脚信息。</p>
</template>
</ChildComponent>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
}
};
</script>
在这个示例中,<ChildComponent>
定义了三个 slot:一个未命名的 default slot 和两个命名 slot “header” 和 “footer”。在 <ParentComponent>
中,使用 v-slot
指令将内容插入到这些 slot 中。注意 default slot 的内容不需要用 v-slot
指令。
总的来说,slot
是一个非常强大的工具,用于构建灵活且可复用的组件。