插槽是在创建组件时设定的一块位置,在后面组件导入注册使用时,在组件标签中写传入设定的那块位置的信息。
所以使用插槽,组件必须使用双标签。
插槽可以分为默认插槽(没有设置插槽名)和具名插槽(设置了插槽名),使用具体使用那种插槽呢?
当组件中只有一个插槽时,就可以用默认插槽,因为传入的数据都在其中;但是如果设置了多个插槽就需要使用具名插槽,插入数据时通过插槽名选择插入那个位置。
具名插槽的创建写法:
- <div>
- <slot name="插槽名1">slot>
- <slot name="插槽名2">slot>
- div>
首先演示一下默认插槽的使用:
在box1.vue中创建组件并设置插槽
- <div class="box1">
-
- <div>我是box1div>
- <slot>slot>
- div>
-
- <style>
- .box1{
- width: 100px;
- height: 100px;
- background-color: aqua;
- }
- style>
在app.vue中导入并向插槽中插入数据:
- <div class="app">
- <h1>app主键h1>
- <Box1>
- <b>我是插入插槽的数据b>
- Box1>
- div>
-
- <script>
-
- import Box1 from "@/components/box1.vue"
- export default {
- components:{
- Box1
- }
- }
- script>
-
- <style>
- .app{
- width: 400px;
- height: 400px;
- background-color: burlywood;
- }
- style>
页面情况:

我们的b标签的就被插入到了插槽中,插槽就是为我们开辟的一块位置,什么都能插入,我们插入一张图片看看
修改app中的代码:
- <div class="app">
- <h1>app主键h1>
- <Box1>
- <img src="./image/m1.jpg" alt="" />
- Box1>
- div>
在运行看一下效果:

此时图片也应该成功插入。
具名插槽用法上有一点点小的区别,不仅需要在创建插槽时命名,再使用时不能像默认插槽那样直接将我们要插入的东西写在组件标签中。
我们在使用时在组件标签中要添加一个template标签并在在其行内用v-slot:插槽名绑定具体的插槽,如:
- <Box>
- <template v-slot:插槽名>
- //要传入的东西
- template>
- Box>
v-slot指令也有语法糖,换一种写法:#插槽名;
展示一下用法:
创建box2.vue组件并创建两个插槽:
- <div class="box2">
- <h3>我是box2h3>
- <slot name="cc1">slot>
- <slot name="cc2">slot>
- div>
- <style>
- .box2{
- width: 200px;
- height: 200px;
- background-color: yellow;
- }
- style>
在app.vue中导入并向插槽中插入数据:
- <div class="app">
- <h1>app主键h1>
- <Box1>
- <img src="./image/m1.jpg" alt="" />
- Box1>
- <Box2>
- <template v-slot:cc1>
- <b>我是box2b><br />
- template>
- <template #cc2>
- <img src="./image/w1.jpg" alt="" />
- template>
- Box2>
- div>
-
- <script>
-
- import Box1 from "@/components/box1.vue"
- import Box2 from "@/components/box2.vue";
- export default {
- components:{
- Box1,
- Box2
- }
- }
- script>
-
- <style>
- .app{
- width: 400px;
- height: 400px;
- background-color: burlywood;
- }
- img{
- width: 50px;
- height: 50px;
- }
- style>
页面效果:
