vue-插槽

1.插槽

了解插槽的使用之前,首先要了解组件,插槽可以用来合成组件,父组件可以很灵活的修改子组件的内容。

2.标签用法

custom-input组件中的内容会替代模板中slot标签的内容,

<div id="app">
			<custom-input>
				vue
			</custom-input>
		</div>
		
		
		<script>
			
			Vue.component("custom-input",
			{
				props:['value'],
				template:`<div>hello,
					<slot></slot>
				</div>`
			});
			
			var app11 = new Vue({
				el:'#app',
				data:{
					searchText:''
				}
				
			})

3.后备内容

slot中间可以添加内容,作为默认内容,如果组件没有添加内容,它将作为默认显示

<div id="app">
			<custom-input :name="name">
			</custom-input>
			
			<custom-input :name="name">
				vue
			</custom-input>
			
		</div>
		
		
		<script>
			
			Vue.component("custom-input",
			{
				props:['name'],
				template:`<div>hello,
					<slot>{{name}}</slot>
				</div>`
			});
			
			var app11 = new Vue({
				el:'#app',
				data:{
					name:'ly'
				}
				
			})

4.具名插槽

在组件模板的定义中,我们可以为slot标签的name属性赋值,在调用组件时,配合template标签和v-slot属性将值赋予对应的插槽,如果没有被tempate和v-slot包裹的元素,将会被传入默认的插槽。

<div id="app">
			<custom-input>
				<template v-slot:header>
					<div>header</div>
				</template>
				
				<div>default slot content</div>
				
				<template v-slot:footer>
					<div>footer</div>
				</template>
				
			</custom-input>
			
			
			
		</div>
		
		
		<script>
			
			Vue.component("custom-input",
			{
				template:`,
					<div>
						<slot name="header"></slot>
						<slot></slot>
						<slot name="footer"></slot>
					</div>`
			});
			
			var app11 = new Vue({
				el:'#app',
				data:{
					name:'ly'
				}
				
			})
			
			
			
			
		</script>

5.作用域插槽

作用域插槽能让插槽内容能访问子组件中的数据,数据在各自的具名插槽中,用v-bind绑定到插槽中,在template元素上,我们在原先的具名插槽上将值赋予一个对象,通过对象,可以访问绑定在插槽上对应的属性
例如:v-slot:header=“header”

<div id="app">
   		<custom-input >
   			<template v-slot:header="header">
   				<p>my name is  {{header.user.name}}</p>
   			</template>
   			
   			<template v-slot:default="slotProps">
   				<p>my age is  {{slotProps.user.age}}</p>
   			</template>
   			
   		</custom-input>
   		
   		
   		
   	</div>
   	
   	
   	<script>
   		
   		Vue.component("custom-input",
   		{
   			template:`
   				<div>
   					<slot name="header" v-bind:user="user">
   						
   					</slot>
   				
   					<slot v-bind:user="user">
   					</slot>
   					
   				</div>`,
   			data:function(){
   				return {
   					user:{
   						name:'ly',
   						age:24,
   						address:'shenzhen'
   					}
   				}
   			}	
   		});
   		
   		var app11 = new Vue({
   			el:'#app',
   			data:{
   				
   			}
   			
   		})
   		
   		
   		
   		
   	</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值