前言 在vue的开发过程中,我们会经常使用到vue的slot插槽组件,vue官方文档的描述: Vue 实现了一套内容分发的 API,这套 API 的设计灵感源自 Web Components 规范草案,将 元素作为承载分发
          在vue的开发过程中,我们会经常使用到vue的slot插槽组件,vue官方文档的描述:
Vue 实现了一套内容分发的 API,这套 API 的设计灵感源自 Web Components 规范草案,将
元素作为承载分发内容的出口 
slot大概分为以下几种:
基础slot组件(匿名插槽)匿名插槽主要使用场景并不涉及特别复杂的业务,更像是纯展示组件内容
<!--子组件-->
<template>
	<span>
		我是基础slot子组件, 父组件传过来的值:
		<span style="color: red"><slot></slot></span>
	</span>
</template>
<!--父组件-->
<li>
    基础slot组件(匿名插槽):<Base>这是一段父组件传过来的文字</Base>
</li>
import Base from "./Base.vue";
具名插槽
具名插槽,需要在父组件和子组件约定插槽名称
<!--子组件-->
<template>
	<span>
		<span style="color: red">
			<slot name="name1"></slot>
			<slot name="name2"></slot>
		</span>
	</span>
</template>
<!--父组件-->
<li>
    <p>具名插槽:</p>
    <Specific>
    	<template v-slot:name1>
    		<p>name1传过来的内容</p>
    	</template>
    	<template v-slot:name2>
    		<p>name2传过来的内容</p>
    	</template>
    </Specific>
</li>
import Specific from "./Specific.vue";
作用域插槽
作用域插槽,子组件提供数据,父组件接收子组件的值并展示和处理逻辑
<!--子组件-->
<template>
	<span>
		<span>
			<slot name="scopeName" v-bind:scopeData="age"></slot>
		</span>
	</span>
</template>
<script lang="ts">
import { Component, Vue, Prop } from "vue-property-decorator";
@Component
export default class Scope extends Vue {
	private age: Number = 23;
}
</script>
<!--父组件-->
<li>
	<p>作用域插槽</p>
	<Scope>
		<template v-slot:scopeName="childData">
			作用域子组件slot返回的数据:
			<span style="color: red">
				{{ childData.scopeData }}
			</span>
		</template>
	</Scope>
</li>
import Specific from "./Specific.vue";
解构插槽
解构插槽,类似在js书写对象过程中的对象解构
{ data:{ username:1 } }
<!--子组件-->
<template>
	<span>
		<p>
			<slot v-bind:user="user"></slot>
		</p>
	</span>
</template>
<script lang="ts">
import { Component, Vue, Prop } from "vue-property-decorator";
@Component
export default class Deconstru extends Vue {
	private user: Object = {
		name: "zhangsan",
		age: 23,
	};
}
</script>
<!--父组件-->
<li>
	<p>解构插槽</p>
	<Deconstru>
		<template v-slot="{ user: person }">
			父组件模板:{{ person.name }},{{ person.age }}
		</template>
	</Deconstru>
</li>
import Specific from "./Deconstru.vue";
以上例子均已上传至开源仓库,后续关于vue的学习笔记均会更在在该项目上,欢迎star
- 码云 https://gitee.com/lewyon/vue-note
 - githup https://github.com/akari16/vue-note
 
总结
在vue的插槽文档中,还有包含
- 
独占默认插槽
 - 
动态插槽名
 - 
具名插槽的缩写
 
<template #footer>
    <p>Here's some contact info</p>
  </template>
详细关于插槽的官方文档传送门
https://cn.vuejs.org/v2/guide/components-slots.html
文章个人博客地址:vue2版本中slot的基本使用详解
欢迎关注公众号:程序员布欧,不定期更新一些技术文章
创作不易,转载请注明出处和作者。
