Vue2中的插槽编写

刚在官网看完了keep-alive,就随手翻了翻,看到了插槽的内容

在 2.6.0 中,我们为具名插槽和作用域插槽引入了一个新的统一的语法 (即 v-slot 指令)。它取代了 slotslot-scope 这两个目前已被废弃但未被移除且仍在文档中的 attribute。

What?大变天了?我好像跟不上时代了,既然都看到了,就把官网的内容再过一遍,会的加深记忆,不会的好好学习一下。

正如vue官网所说,slot和slots-cope已经被废弃了,虽然在vue2.x中仍然被支持,但是不会出现到vue3中,就借此机会把官网有关于插槽的内容过一遍。

默认插槽

组件中的内容就默认加载到默认插槽中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!-- 子组件 -->
<template>
<div>
<h1>子组件的内容</h1>
<!-- 插槽 -->
<slot></slot>
</div>
</template>

<!-- 父组件 -->
<Child>
<!-- 父组件标签内的内容会放到默认插槽 -->
<h3>
父组件要放入子组件插槽中的内容
</h3>
</Child>

具名插槽

当子组件中存在多个插槽时,则需要对插槽进行命名用于区分

不对插槽命名则会有默认名为default

1
2
3
4
5
6
7
8
9
<!-- 子组件child -->
<template>
<div>
<h1>Title</h1>
<!-- 插槽 -->
<slot name="slot1"></slot>
<slot name="slot2"></slot>
</div>
</template>

使用新的slot语法

1
2
3
4
5
6
7
8
9
10
11
12
<!-- 父组件 -->
<Child>
<!-- v-slot:可以用#代替简写为<template #slot1> -->
<template v-slot:slot1>
<img />
<a />
</template>
<template #slot2>
<img />
<a />
</template>
</Child>

作用域插槽

slot-scope语法已经被废弃,我们现在使用带值的v-slot来访问作用域插槽

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!-- 子组件child -->
<template>
<div>
<h1>Title</h1>
<!-- 插槽: 这里传递的数据会传给插槽的使用者 -->
<slot :games="games"></slot>
</div>
</template>
<script>
export default {
data(){
return {
games: []
}
}
}
</script>


<!-- 父组件 -->
<template>
<!-- -->
<Child>
<!-- slotProps包含插槽的所有prop,当然可以自己随意定义名字 -->
<!-- 这里使用了默认插槽,所以可以不指定插槽名字为default -->
<template v-slot="slotProps">
<!-- 这里可以使用插槽传递的数据了 -->
<ul> <!-- games就是插槽传递出来的 -->
<li v-for="item in slotProps.games">{{item}}</li>
</ul>
</template>
</Child>
</template>

也可以将数据解构使用

1
2
3
4
5
6
7
8
9
10
11
12
<!-- 父组件 -->
<template>
<!-- -->
<Child>
<!-- 可以将数据解构使用 -->
<template v-slot:default="{games}">
<ul>
<li v-for="item in games">{{item}}</li>
</ul>
</template>
</Child>
</template>

也是可以使用缩写形式的:

1
2
3
4
5
6
7
8
9
10
11
12
<!-- 父组件 -->
<template>
<!-- -->
<Child>
<!-- 使用缩写必须使用明确的插槽名,默认插槽也不能省略 -->
<template #default="{games}">
<ul>
<li v-for="item in games">{{item}}</li>
</ul>
</template>
</Child>
</template>
作者

胡兆磊

发布于

2022-03-31

更新于

2022-10-23

许可协议