1、什么是插槽
<slot></slot>
插槽: 是一个预留的位置,父组件在使用子组件时候在子组件标签中的内容会填充到slot
的位置
2、 插槽的分类
2.1 默认插槽
直接写在组件标签中的内容会填充到默认的插槽中
// 父组件 app.vue
<template>
<p>这是子父组件</p>
<slotDemo>
<!-- 直接写在子组件中的内容,会填充到默认的插槽中(没有name shuxing ) -->
<p>填充到默认插槽中<p>
</slotDemo>
</template>
// 子组件 slotDemo.vue
<template>
<p>这是子组件</p>
<!-- 插槽:预留的位置,父组件中p标签中的内容自动填充到此位置 -->
<slot></slot>
</template>
2.2 具名插槽
通过 name
属性给插槽起名字,带有 name
的插槽叫做具名插槽。
// 父组件 app.vue
<template>
<p>这是子父组件</p>
<slotDemo>
<!--父组件通过如下形式将这部分模板片段传入子组件的 header 插槽中-->
<template v-slot:header></template>
<!-- 也可以简写成一下形式-->
<template #footer></template>
</slotDemo>
</template>
// 子组件 slotDemo.vue
<template>
<p>这是子组件</p>
<!-- 插槽:预留的位置,父组件中标签的内容通过name填充到不同的位置 -->
<header>
<slot name="header"></slot>
</header>
<footer>
<slot name="footer"></slot>
</footer>
</template>
3.2 作用域插槽
父组件在使用子组件的时候能获得传过来的数据,子组件在渲染时将一部分数据提供给插槽。
在定义插槽的时候把一些数据传递出去,可以像组件传props 那样向插槽的出口传递(如:item=“info”)
注: 默认插槽和具名插槽在接收子组件传递的插槽props 时有些许不同
3.2.1 默认插槽
// 父组件 app.vue
<template>
<p>这是子父组件</p>
<slotDemo>
<p v-slot="slotProps">{{slotProps.item}}-- {{slotProps.count}}</p>
</slotDemo>
</template>
// 子组件 slotDemo.vue
<template>
<p>这是子组件</p>
<header>
<slot :item="info" :count="1"></slot>
</header>
</template>
3.2.2 具名插槽
// 父组件 app.vue
<template>
<p>这是子父组件</p>
<slotDemo>
<p v-slot:header="slotProps">{{slotProps.item}}-- {{slotProps.count}}</p>
</slotDemo>
</template>
// 子组件 slotDemo.vue
<template>
<p>这是子组件</p>
<header>
<slot name="header" :item="info" :count="1"></slot>
</header>
</template>
如果同时使用具名插槽与默认插槽,则需要为默认插槽使用显式的 标签
例如:
<template>
<MyComponent>
<!-- 使用显式的默认插槽 -->
<template #default="{ message }">
<p>{{ message }}</p>
</template>
<template #footer>
<p>Here's some contact info</p>
</template>
</MyComponent>
</template>