Vue插槽

插槽概念

父组件向子组件指定位置插入 html 结构,也可以适用于父子组件之间的通信

分类:

  1. 默认插槽
  2. 具名插槽
  3. 作用域插槽

使用方式

默认插槽

<!-- 父组件中写法 -->
<template>
	<son>
		<div>
			Your Profile
		</div>
	</son>
</template>

<!-- 子组件中写法 -->
<template>
	<div>
		<!-- 定义插槽 -->
		<slot>
		插槽默认内容(如果父组件中没有传递内容,则展示默认内容)
		</slot>
	</div>
</template>

在父组件使用了子组件,在组件标签中填写内容(Your profile),就会展示在子组件 slot 相应的位置

具名插槽

<!-- 父组件中写法 -->
<template>
	<son>
		<template slot="position1">
			<div>
				Your Profile!
			</div>
		</template>
	
		<template v-slot:position2>
			<div>
				Your Profile!!!
			</div>
		</template>
	</son>
</template>

<!-- 子组件中写法 -->
<template>
	<div>
		<!-- 定义插槽 -->
		<slot name="position1">插槽默认内容</slot>
		<slot name="position2">插槽默认内容</slot>
	</div>
</template>

在父组件的 template 结构中,使用 slot=“xx” 或者 v-slot:“xx”,标识当前结构中的内容(Your profile),展示在子组件中哪个位置。

作用域插槽

数据在组件自身,但根据数据生成的结构需要组件的使用者来决定。
即当数据在子组件,而在父组件中使用子组件时,无法使用子组件中的数据,所以此时需要作用域插槽。

<!-- 父组件中 -->
<template>
	<son>
		<template scope="scopeData">
			<ul>
				<li v-for"book in scopeData.books" :key="book">
					{{book}}
				</li>
			</ul>
		</template>
	</son>
</template>
<!-- 子组件中 -->
<template>
	<div>
		<slot :books="books"></slot>
	</div>
</template>
<script>
	export default {
		name:"son"
		data() {
			return {
				books:['三国','春秋','左传']
			}
		}
	}
</script>

使用 scope=“xx” 或 slot-scope=“xx”,可以接收到子组件的数据,然后渲染在父组件中。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值