插槽就是Vue实现的一套内容分发的API,将元素作为承载分发内容的出口。
插槽,也就是槽,是组件的一块HTML模板,这块模板显示不显示,以及怎样显示由父组件来决定
但是插槽显示的位置却由子组件自身决定,槽写在组件模板的什么位置,父组件传过来的模板将来就显示在什么位置
匿名插槽
匿名插槽可以放置在组件的任意位置,但是就像它的名字一样,一个组件中只能有一个该类插槽。
// 父组件
<template>
<div class="father">
<h3>这里是父组件</h3>
<child>
<div class="tmpl">
<span>菜单1</span>
<span>菜单2</span>
<span>菜单3</span>
</div>
</child>
</div>
</template>
// 子组件
<template>
<div class="child">
<h3>这里是子组件</h3>
<slot></slot> //如果没有这一行,父组件里面child中间的内容将不展示
</div>
</template>
具名插槽
匿名插槽加了名称属性,就变成了具名插槽;具名插槽可以在一个组件中出现Ñ次,出现在不同的位置。
具名插槽就可以有很多个,只要名字(名称属性)不同就可以了
// 父组件
<template>
<div class="father">
<h3>这里是父组件</h3>
<child>
<div class="tmpl" slot="up">
<span>菜单1</span>
<span>菜单2</span>
</div>
<div class="tmpl" slot="down">
<span>菜单-1</span>
<span>菜单-2</span>
</div>
<div class="tmpl">
<span>菜单->1</span>
<span>菜单->2</span>
</div>
</child>
</div>
</template>
//子组件
<template>
<div class="child">
// 具名插槽
<slot name="up"></slot>
<h3>这里是子组件</h3>
// 具名插槽
<slot name="down"></slot>
// 匿名插槽
<slot></slot>
</div>
</template>
作用域插槽
这个插槽解决的问题不仅仅是可以在子组件中动态地放置一段html代码片段,而且还可以取到子组件中相应的一些值。
我们给元素上定义一个属性say(随便定义的!),接下来在使用组件child,然后在template元素上添加属性slot-scope!!随便起个名字scopeName,我们把scopeName打印一下发现是 {"say" : "你好"},也就是slot上面的属性和值组成的键值对!!!
使用时候子组件标签中要有