认识插槽Slot
- 在开发中经常封装一个个可复用的组件:
- 前面通过props传递给组件一些数据,让组件来进行展示;
- 但是为了让这个组件具备更强的通用性,不能将组件中的内容限制为固定的div、span等等元素;
- 比如某种情况下希望组件显示的是一个按钮,某种情况下希望显示的是一张图片;
- 所以,应该让使用者可以决定某一块区域到底存放什么内容和元素;
如何使用插槽slot?
- 定义插槽slot:
- 插槽的使用过程其实是抽取共性、预留不同;
- 将共同的元素、内容依然在组件内进行封装;
- 同时会将不同的元素使用slot作为占位,让外部决定到底显示什么样的元素;
- 如何使用slot呢?
- Vue中将
元素作为承载分发内容的出口; - 在封装组件中,使用特殊的元素
就可以为封装组件开启一个插槽; - 该插槽插入什么内容取决于父组件如何使用;
- Vue中将
插槽的基本使用
一个组件MySlotCpn.vue:该组件中有一个插槽,我们可以在插槽中放入需要显示的内容;
我们在App.vue中使用它们:可以插入普通的内容、html元素、组件元素,都可以是可以的;
<template>
<div>
<test>
我是文字~~
<button>按钮</button>
<!--这里是外部引入的组件-->
<button-test></button-test>
</test>
</div>
</template>
<script>
import Test from "./Test.vue";
import ButtonTest from "./ButtonTest.vue";
export default {
name: "App",
components: {
Test,
ButtonTest,
},
};
</script>
<template>
<div>
<h3>test</h3>
<slot></slot>
</div>
</template>
<script>
export default {
name: "test",
};
</script>
这样,父组件中test标签中的全部内容,就回插入到子组件中slot的位置。
插槽的默认内容
在使用插槽时,如果没有插入对应的内容,则显示一个默认的内容
如果一个组件中含有多个插槽,我们插入多个内容时是什么效果?
- 默认情况下每个插槽都会获取到我们插入的内容来显示;
<template>
<div class="bar">
<div class="left">
<slot></slot>
</div>
<div class="center">
<slot></slot>
</div>
<div class="right">
<slot></slot>
</div>
</div>
</template>
<style scoped>
.bar {
display: flex;
}
.left,
.right {
width: 100px;
background-color: pink;
height: 50px;
}
.center {
flex: 1;
background-color: hotpink;
}
</style>
具名插槽的使用
我们希望达到的效果是插槽和内容对应显示,此时可以使用具名插槽:
- 具名插槽顾名思义就是给插槽起一个名字,
元素有一个特殊的 attribute:name; - 一个不带 name 的slot,会带有隐含的名字 default;
<test> <template v-slot:left>我是文字~~</template> <template v-slot:default><button>按钮</button></template> <template v-slot:right><button-test></button-test></template> </test>
<template> <div class="bar"> <div class="left"> <slot name="left"></slot> </div> <div class="center"> <slot></slot> </div> <div class="right"> <slot name="right"></slot> </div> </div> </template>
动态插槽名
- 具名插槽顾名思义就是给插槽起一个名字,
什么是动态插槽名呢?
- 目前我们使用的插槽名称都是固定的;
- 比如 v-slot:left、v-slot:center等等;
- 可以通过 v-slot:[dynamicSlotName]方式动态绑定一个名称;
```vue
{{ cos.item }} - {{ cos.i }}

<a name="nP0AT"></a>
## 独占默认插槽的缩写
如果我们的插槽是默认插槽default,那么在使用的时候 `v-slot:default="slotProps"`可以简写为`v-slot="slotProps"`
```vue
<slot-item :list="list">
<template v-slot="slotProps">
<h3>{{ slotProps.names }}</h3>
<p>{{ slotProps.age }}</p>
</template>
</slot-item>
并且如果我们的插槽只有默认插槽时,组件的标签可以被当做插槽的模板来使用,这样,我们就可以将 v-slot 直
接用在组件上:
<slot-item :list="list" v-slot="slotProps">
<h3>{{ slotProps.names }}</h3>
<p>{{ slotProps.age }}</p>
</slot-item>
默认插槽和具名插槽混合
但是,如果我们有默认插槽和具名插槽,那么按照完整的 只要出现多个插槽,请始终为所有的插槽使用完整的基于 的语法:
template
编写。否则会存在问题
当存在其他命名插槽时,默认插槽必须在自定义元素上使用“”。
<slot-item :list="list">
<!-- 默认插槽 -->
<template v-slot="slotProps">
<h3>{{ slotProps.names }}</h3>
<p>{{ slotProps.age }}</p>
</template>
<!-- 具名插槽 -->
<template v-slot:cos>
<button>cos</button>
</template>
<!-- 具名插槽,传递参数 :是名称 =后面是参数 -->
<template v-slot:rose="slotProps">
<button>{{ slotProps.names }}</button>
</template>
</slot-item>