在Vue.js中,slot主要有以下几种类型:
-
默认插槽(Default Slot) 默认插槽是最常见的一种插槽类型,即没有名称的插槽。当父组件在子组件标签内部放置的所有内容都会被传递到子组件的默认插槽中。
<!-- 子组件 --> <template> <div class="card"> <header>标题</header> <slot></slot> <!-- 这里是默认插槽 --> </div> </template> <!-- 父组件 --> <template> <child-component> <p>这是从父组件传入的内容,默认插槽部分。</p> </child-component> </template>
-
具名插槽(Named Slots) 具名插槽允许开发者定义具有特定名称的插槽,从而在子组件中以更精细的方式控制内容的插入位置。
<!-- 子组件 --> <template> <div class="custom-layout"> <header><slot name="header"></slot></header> <main><slot name="main"></slot></main> <footer><slot name="footer"></slot></footer> </div> </template> <!-- 父组件 --> <template> <child-component> <h1 slot="header">这是头部内容</h1> <section slot="main">这是主要内容区域</section> <p slot="footer">这是底部内容</p> </child-component> </template>
-
作用域插槽(Scoped Slots) 作用域插槽允许父组件访问子组件的数据并在插槽内容中使用这些数据。
<!-- 子组件 --> <template> <div> <!-- 定义一个带有作用域插槽的列表 --> <ul> <li v-for="item in items" :key="item.id"> <!-- 将当前循环项的详细信息传递给父组件 --> <slot :item="item"></slot> </li> </ul> </div> </template> <script> export default { data() { return { items: [ { id: 1, text: "苹果", detail: "这是一种水果" }, { id: 2, text: "香蕉", detail: "这也是种水果" }, // 更多... ], }; }, }; </script> <!-- 父组件 --> <template> <div> <Bpp> <!-- 使用 v-slot 接收并处理子组件传递的数据 --> <!-- 在这里我们通过 slotProps 访问子组件传递的 item 数据 --> <template v-slot="slotProps"> <p>名称:{{ slotProps.item.text }}</p> <p>详情:{{ slotProps.item.detail }}</p> <hr /> {{ slotProps.item }} {{ slotProps }} </Bpp> </div> </template> <script> import Bpp from "./Bpp.vue"; export default { components: { Bpp, }, }; </script>
下面这个示例可能更直观的看到子组件是如何给父组件传值的
-
// 父组件 <template> <div> <Bpp> <!-- 使用 v-slot 接收并处理子组件传递的数据 --> <!-- 在这里我们通过 slotProps 访问子组件传递的 item 数据 --> <template v-slot="slotProps"> <hr /> {{ slotProps.item }} <hr /> {{ slotProps }} </template> </Bpp> </div> </template> <script> import Bpp from "./Bpp.vue"; export default { components: { Bpp, }, }; </script> //子组件 <template> <div> <slot :item="items"></slot> </div> </template> <script> export default { data() { return { items: [ { id: 1, text: "苹果", detail: "这是一种水果" }, { id: 2, text: "香蕉", detail: "这也是种水果" }, ], }; }, }; </script>
在上述示例中,v-slot
(在Vue 2.x 中也写作 slot
)是Vue 2.6+引入的新语法糖,用于更加晰地表示插槽的使用。在早期版本中,需要使用 slot
属性配合 <template>
标签实现类似的功能。在Vue 3.x中,v-slot
已经成为标准语法。
Vue 3.x 中使用 <script setup>
和 <slot>
结合 defineSlots
等新特性来定义和使用插槽。