vue插槽的使用

1、什么是插槽

1、插槽就是在子组件中提供父组件一个占位符,用于用户填充任何自己所需求的模板代码,
2、插槽显不显示、怎样显示是由父组件来控制的,而插槽在哪里显示在什么位置就由子组件来进行控制
3、可以把插槽认为是组件封装期间,为用户预留的内容的占位符。

2、什么时候使用插槽

当子组件被复用时,需要在特定的区域展示不同的需求内容

3.使用

3.1.匿名插槽(默认插槽)

1
2
3
4
5
6
7
8
9
10
<!--父组件内容-->
<template>
<div>
<!--子组件标签-->
<Category>
<!--子组件标签体内容,也就是需要插入的内容-->
<a href="#" slot="footer">更多信息</a>
</Category>
</div>
</template>
1
2
3
4
5
6
7
<!--子组件内容-->
<template>
<div>
<!-- 在<slot>标签位置显示插入的内容-->
<slot></slot>
</div>
</template>

3.2.具名插槽

需要使用多个插槽的时候,定义一个 name 属性,区分插槽对应的位置。

1
2
3
4
5
6
7
8
<template>
<div>
<Category>
<img slot="center" src=""/>
<a slot="footer" href="#">更多信息</a>
</Category>
</div>
</template>
1
2
3
4
5
6
7
8
9
10
<!--子组件内容-->

<template>
<div class="category">
<slot name="center"> slot标签,这个位置也可以写内容 </slot>
<slot name="footer"></slot>
</div>
</template>
<!-- slot="center" 对应 name="center" -->
<!-- slot="footer" 对应 name="footer" -->

3.3.作用域插槽

当父组件需要用到子组件里的数据时,通过插槽传递数据。

1
2
3
4
5
6
7
8
9
10
11
12
13
<!--父组件内容-->
<template>
<div class="container">
<Category >
<!--需要包裹一个template标签(必须),获取slot传递数据-->
<template slot="link"
slot-scope="scope">
<span v-for="item in scope.data"
:key="item">{{item}}</span>
</template>
</Category>
</div>
</template>
1
2
3
4
5
6
7
<!--子组件内容-->
<template>
<div class="category">
<!--通过slot传递数据data-->
<slot :data="data">test</slot>
</div>
</template>

vue插槽的使用
http://example.com/2022/12/12/vue插槽的使用/
作者
dinghw
发布于
2022年12月12日
许可协议