插槽分类
- 默认插槽(匿名插槽)(单个插槽)
- 具名插槽
- 作用域插槽
插槽的作用
让父组件可以向子组件指定位置插入html结构,也是一种组件间通信的方式。插槽显示不显示,怎么显示,是父组件及控制。显示在什么位置,是子组件控制。
使用方式
1.默认插槽
// 父组件
<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>
</div>
</template>
2.具名插槽
// 父组件
<template>
<div class="father">
<h3>这里是父组件</h3>
<child>
// 这里可以使用v-slot。vue2.6以后提出的,但是,必须写在template上面,否则报错,v-slot可以简写成#
// <template v-slot:a>
// <template #a>
<div class="tmpl" slot="a">
<span>菜单1</span>
<span>菜单2</span>
<span>菜单3</span>
</div>
<div class="tmpl" slot="b">
<span>菜单-1</span>
<span>菜单-2</span>
<span>菜单-3</span>
</div>
<div class="tmpl">
<span>菜单->1</span>
<span>菜单->2</span>
<span>菜单->3</span>
</div>
</child>
</div>
</template>
// 子组件
<template>
<div class="child">
// 具名插槽
<slot name="a"></slot>
<h3>这里是子组件</h3>
// 具名插槽
<slot name="b"></slot>
// 匿名插槽
<slot></slot>
</div>
</template>
3.作用域插槽
这个插槽,可能有点难理解,但是还是有使用场景的,就是数据不在父组件,而是在子组件中的时候
// 父组件
<template>
<div class="father">
<h3>这里是父组件</h3>
<child>
// <template scope="childData">
// 上面是以前的写法,下面是新的写法,都可以
// 这里必须是template
<template slot-scope="childData">
<span v-for="(item,index) in childData.lists" :key="index">{{item}}</span>
</template>
</child>
</div>
</template>
// 子组件
<template>
<div class="child">
<slot :lists="list"></slot>
</div>
</template>
data() {
return {
list: ['菜单1','菜单2','菜单3']
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。