# slot

# 什么是slot

  • 可以理解为预留了一个可替换的地方(小霸王游戏机的插卡位置)

# 为什么需要slot

  • 可扩展性(插入不同的游戏卡可以玩不同的游戏)
  <div id="app">
    <!-- 使用组件 -->
    <son>
      <h2>我是h2标题</h2>
    </son>
  </div>

  <!-- 定义组件 -->
  <template id="tmp">
    <div>
      <slot></slot>
    </div>
  </template>
1
2
3
4
5
6
7
8
9
10
11
12
13
  const vm = new Vue({
      el: '#app',
      components: {
        // 组件名:组件对象
        son: {
          template: '#tmp'
        }
      }
    })
1
2
3
4
5
6
7
8
9
  1. 将son标签中的<h2>我是h2标题</h2>插到<slot></slot>位置:∴由<div><slot></slot></div>变成了<div><h2>我是h2标题</h2></div>
  2. 替换整个son标签,最终为:
  <div id="app">
    <div><h2>我是h2标题</h2></div>
  </div>
1
2
3

# slot分类

# 具名插槽

  • 使用多个插槽时,需要给插槽取名字区分开来
  <div id="app">
    <son>
      <h2>我是h2标题</h2>
      <div slot="cpu">我是cpu</div> <!-- 是哪个插槽 -->
      <div slot="memory">我是memory</div>
    </son>
  </div>
1
2
3
4
5
6
7
  <template id="tmp">
    <div>
      <slot></slot>
      <slot name="cpu"></slot>
      <slot name="memory"></slot>
    </div>
  </template>
1
2
3
4
5
6
7

# 作用域插槽

  • 父组件的模板中需要用到子组件状态的时候,需要使用作用域插槽
  <div id="app">
    <button v-show="isShow">父按钮</button>
    <son v-slot:default="prop">
      <!-- 通过v-slot找到default插槽,跟父组件的prop对象对应起来 -->
      <button v-show="prop.show">我是标题</button>
    </son>
  </div>
1
2
3
4
5
6
7
  <template id="tmp">
    <div>
      <slot :show="isShow"></slot>
    </div>
  </template>
1
2
3
4
5