# 6.组件插槽

# 匿名插槽

当 slot 没有指定 name 属性值的时候一个默认显示插槽,一个组件内只有有一个匿名插槽。

  1. 组件复用的时候用到:

    组件1中:
    <div> <div/>
    <slot> <slot/>//这里到时候就会替换
    
    使用组件1<component1><div> <div/><component1/>  里面的div就会替换slot的区域
    
    1
    2
    3
    4
    5
    6

# 具名插槽

<div>
  <p>我是子组件</p>
  <p>我是一行话</p>
  <slot name="default">这是占位的内容</slot>
  <slot name="t1">这是t1占位的内容</slot>
  <slot name="t2">这是t2占位的内容</slot>
  <slot name="t3">这是t3占位的内容</slot>
  <slot name="t5">这是t4占位的内容</slot>
</div>
<child>
  <!-- 此时这两句话还是放在匿名插槽中 -->
  <h1 style="color: aqua;">这是第一个内容</h1>
  <h1 style="color: red;">这第二个内容</h1>
  <!-- slot="t1"  指定把内容放在那个插槽里 -->
  <h2 style="color: blue;" slot="t1">我要放在具名插槽t1里使用</h2>
  <h3 style="color: green;" slot="t2">我要放在具名插槽t2里使用</h3>
  <h4 style="color: orange;" slot="t3">我要放在具名插槽t3里使用</h4>
  <h5 style="color: pink;" slot="t4">我要放在具名插槽t4里使用</h5>
</child>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

# 父组件获取子组件插槽中的数据(vue3.0 是 v-slot)

组件1<div>
	<slot :data="left"> <slot/>//名字任取
<div/>
使用组件1<component1>
    <template slot-scop="slot"> //这样兼容性更好,slot名字自定义
        <span v-for="item in slot.data"> <span/>
    <template/>
<component1/>
1
2
3
4
5
6
7
8
9
10
Last Updated: 6/3/2024, 1:08:34 AM