初识 Vue(19)---(Vue 中使用插槽(slot))

本文介绍了在 Vue 中如何使用插槽解决子组件内容由父组件传递的问题,包括无名插槽和具名插槽的使用,以及插槽设置默认样式的方法。通过插槽,可以提高代码的可读性和组件的复用性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Vue 中使用插槽(slot)

案例:子组件中的一部分内容是根据父组件传递来的 DOM 来进行显示

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Vue 中使用插槽(slot)</title>
	<script src="./vue.js"></script>
</head>
<body>
	<div id="root">
		<child content='<p>Dell</p>'></child>
	</div>	
	<script>
	Vue.component('child',{
		props:['content'],
		template:'<div><p>hello</p><div v-html="this.content"></div></div>'
		
	})

	var vm = new Vue({
		el:'#root',
		
		})
	</script>
</body>
</html>

输出:

存在问题:1.通过 content 传值,想直接使用里面的 <p> ,必须在外面包裹一层 DIV;

2.用这种方法向子组件传值时,当传递的数值过多时会造成代码可读性很差

 

子组件中的一部分内容是根据父组件传递来的 DOM 来进行显示的时候,可以使用插槽的方法

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Vue 中使用插槽(slot)</title>
	<script src="./vue.js"></script>
</head>
<body>
	<div id="root">
		<child>
			<p>Dell</p>  
		</child>
	</div>	
	<script>
	Vue.component('child',{
		props:['content'],
		//获取插槽内容
		template:'<div> <p>Hello</p><slot></slot></div>'
		
	})

	var vm = new Vue({
		el:'#root',
		
		})
	</script>
</body>
</html>

输出:

slot 还可以设置默认样式

<body>
	<div id="root">
		<child>
			 
		</child>
	</div>	
	<script>
	Vue.component('child',{
		props:['content'],
		//获取插槽内容
		template:'<div> <p>Hello</p><slot>默认内容</slot></div>'
		
	})

输出:

功能:输出,其中 header 部分和 footer  部分均由父组件传入

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Vue 中使用插槽(slot)</title>
	<script src="./vue.js"></script>
</head>
<body>
	<div id="root">
		<body-content>
			  <div class="header" slot='header'>header</div>
			  <div class="footer" slot='footer'>footer</div>
		</body-content>
	</div>	
	<script>
	Vue.component('body-content',{

		//获取插槽内容
		template:'<div>
                  <slot name='header'></slot>
                   <div class='content'>content</div>
                    <slot name='footer'></slot>
                    </div>'
		
	})

	var vm = new Vue({
		el:'#root',
		
		})
	</script>
</body>
</html>

给每一个插槽给定具体的名字称为 具名插槽(可以有多个,也可以有默认值,但插槽只能有一个)

输出:

具名插槽 默认值

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Vue 中使用插槽(slot)</title>
	<script src="./vue.js"></script>
</head>
<body>
	<div id="root">
		<body-content>
	
			  <div class="footer" slot='footer'>footer</div>
		</body-content>
	</div>	
	<script>
	Vue.component('body-content',{

		//获取插槽内容
		template:'<div>
                  <slot name='header'>default header</slot>
                   <div class='content'>content</div>
                    <slot name='footer'></slot>
                    </div>'
		
	})

	var vm = new Vue({
		el:'#root',
		
		})
	</script>
</body>
</html>

输出:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值