Vue 插槽
插槽是 Vue 中一个强大的功能,它允许更灵活和可重用的组件。
我们使用 Vue 中的插槽将父组件的内容发送到子组件的 <template>
中。
插槽
到目前为止,我们只在 <template>
中将组件用作自闭合标签,例如:
App.vue
:
<template>
<slot-comp />
</template>
相反,我们可以使用开闭标签,并在其中放置一些内容,例如一段文本:
App.vue
:
<template>
<slot-comp>Hello World!</slot-comp>
</template>
但要接收 'Hello World!' 并将其显示在我们的页面上,我们需要在组件中使用 <slot>
标签。<slot>
标签充当内容的占位符,因此在应用程序构建后,<slot>
将被发送给它的内容替换。
插槽作为卡片
插槽也可用于包装大块的动态 HTML 内容,以获得卡片式外观。
之前我们通过 props 发送数据来创建组件内部的内容,现在我们可以直接将 HTML 内容作为内容发送到 <slot>
标签中。
示例
App.vue
:
<template>
<h3>Slots in Vue</h3>
<p>We create card-like div boxes from the foods array.</p>
<div id="wrapper">
<slot-comp v-for="x in foods">
<img v-bind:src="x.url">
<h4>{{x.name}}</h4>
<p>{{x.desc}}</p>
</slot-comp>
</div>
</template>
当内容进入带有 <slot>
的组件时,我们在 <slot>
周围使用 div 并本地化样式化 <div>
,以在内容周围创建卡片式外观,而不会影响我们应用程序中的其他 div。
SlotComp.vue
:
<template>
<div> <!-- This div makes the card-like appearance -->
<slot></slot>
</div>
</template>
<script></script>
<style scoped>
div {
box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
border-radius: 10px;
margin: 10px;
}
</style>
运行示例 »
可以重用生成卡片式框架内容的组件来创建不同的元素,但它们都带有相同的卡片式框架。
在这个例子中,我们使用与食物项相同的组件来创建一个页脚。
示例
App.vue
:
<template>
<h3>Reusable Slot Cards</h3>
<p>We create card-like div boxes from the foods array.</p>
<p>We also create a card-like footer by reusing the same component.</p>
<div id="wrapper">
<slot-comp v-for="x in foods">
<img v-bind:src="x.url">
<h4>{{x.name}}</h4>
</slot-comp>
</div>
<footer>
<slot-comp>
<h4>Footer</h4>
</slot-comp>
</footer>
</template>
运行示例 »
备用内容
如果没有为组件提供内容,我们可以在 <slot>
中设置备用内容。
示例
此应用程序中的第一个组件没有提供内容,因此会渲染备用内容。
App.vue
:
<template>
<h3>Slots Fallback Content</h3>
<p>A component without content provided can have fallback content in the slot tag.</p>
<slot-comp>
<!-- Empty -->
</slot-comp>
<slot-comp>
<h4>This content is provided from App.vue</h4>
</slot-comp>
</template>
SlotComp.vue
:
<template>
<div>
<slot>
<h4>This is fallback content</h4>
</slot>
</div>
</template>
运行示例 »