# 34.组件插槽基本用法
# 1.匿名插槽
1).插槽位置
Vue.component('alert-box', {
template:`
<div class="demo-alert-box">
<strong>Error!</strong>
<slot></slot>
</div>
`
})
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
2).插槽内容
<alert-box>Something bad happened</alert-box>
1
# 2.具名插槽
- 具有名字的插槽
- 使用
<slot>
中的 "name" 属性绑定元素
1).插槽定义
<div class="container">
<header>
<slot name="header"></slot>
</header>
<main>
<slot></slot>
</main>
<footer>
<slot name="footer"></slot>
</footer>
</div>
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
2).插槽内容
<base-layout>
<h1 slot="header">标题内容</h1>
<p>主要内容1</p>
<p>主要内容2</p>
<p slot="footer">底部内容</p>
</base-layout>
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 3.作用域插槽
- 应用场景: 父组件对子组件的内容进行加工处理
- 既可以复用子组件的slot,又可以使slot内容不一致
- slot大家看看文档都懂了,无非就是在子组件中挖个坑,坑里面放什么东西由父组件决定。
- 作用域插槽实际上是带有数据的插槽, 父组件可以拿到子组件的数据, 修改样式。子组件提供数据
- 作用域插槽,父组件只需要提供一套样式(在确定用作用域插槽绑定的数据的前提下)
- 总结一下,作用域插槽适合的场景是至少包含三级以上的组件层级,是一种优秀的组件化方案!

1).插槽定义
<!-- 子组件 -->
<ul>
<li :key="item.id" v-for="item in list">
<!-- info 是自定义的-->
<slot :info="item">
{{item.name}}
</slot>
</li>
</ul>
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
2).插槽内容
<!-- 父组件 -->
<fruit-list :list="list">
<!-- 传入子组件的自定义内容,会填入到子组件的slot插槽中 -->
<!-- 而父组件通过slot-scope绑定的对象下拿到info的值。-->
<template slot-scope="scope"> <!-- 这里就将下边的内容 显示到了slot插槽中 -->
<strong v-if="scope.info.id==2" class="current">{{scope.info.name}}</strong>
<span v-else>{{scope.info.name}}</span>
</template>
</fruit-list>
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
- slot-scope="scope" ----> 这是作用域插槽中定义一个对象(这里对象被定义为scope)来存储插槽上绑定的数据的用法
- 我的解释 (scope.row ):
// :row 可以设置行内内置对象 index可以用来设置索引
// 这是 Element-ui 内置的插槽 (因为是高度封装, 是看不见的, 别纠结, 当是elementui给出的用法)
// 顺便补充一个知识点: {{scope.$index}}可以获取当前行的index。
<slot :row="item" :$index="i"></slot>
1
2
3
4
2
3
4
← 33.组件插槽的作用 35.购物车案例 →