首页 > 技术文章 > 插槽

lora404 2020-02-22 15:43 原文

使用场景:用于父组件传递DOM元素给子组件
在没有插槽的情况下组件标签内的内容无法被显示,而在组件声明<slot>元素后,标签的内容就会跑到这里。
具名插槽:
插槽有名字,就可以在特定的区域应用特定的插槽内容;没有名字视为默认插槽。
具体实现为在组件标签内定义属性slot,为内容添加名字;而在组件的<slot>中添加name属性,与标签slot属性一一对应。
	<div id='app'>
	<child>
		<header slot='header'>header</header>
		<footer slot='footer'>footer</footer> //具名插槽
	</child>
	</div>

 

		var Child={
			props:['content'],
			data:function() {
				return {num:this.content}
			},
			template:`<div>
			<slot name='header'>default</slot>
			<div class='content'>content</div>
			<slot name='footer'>default</slot>
			</div>`
		}
		var app = new Vue({
			el: '#app', //接管范围
			components: {
				Child:Child
			}
		})
 
作用域插槽(较难理解):让插槽内容能够访问子组件才有的数据时是很有用的。
子组件可以在slot标签上绑定属性值,父组件可以拿到子组件的数据;这个与在子组件中使用$emit向父组件传递数据的功能有类似。
<child>
		<template slot-scope="scope">
			<li>{{scope.item}}</li> <!--展示形式-->
		</template>
	</child>

template是固定写法,必需的;scope是从子组件接收信息的存放处

 

		var Child={
			data:function() {
				return {
					list:[0,1,2,3,4,5]
				}
			},
			template:`<div>
			<ul>
			<slot v-for="item of list" :item=item></slot>
			</ul>
			</div>`
		}

 

子组件简历列表循环并通过绑定item向父组件传值

 

推荐阅读