# 插槽

  1. 当子组件中只没有slot,那么在父组件使用子组件时,子组件标签中的所有内容都会丢失
  2. 当子组件中有一个没有属性得slot,那么父组件在使用子组件时,子组件标签中的所有内容会全部插入到slot所在的DOM位置,同名插槽后面内容会覆盖前面内容
  3. 子组件中通过v-bind可以传递数据
  4. 子组件可以使用父组件的作用域插槽

# 默认插槽:

  • 其实就是namedefault的具名插槽
<template>
  <div>
    <span>Hello</span>
    <!-- name: default -->
    <slot></slot>
  </div>
</template>
  • 调用组件
<template>
  <child>
    World
  </child>
</template>

# 具名插槽

  • 通过name属性定义插槽的名称
<template>
  <div>
    <slot name="name">
  </div>
</template>
  • 调用组件
<template>
  <child>
    <p slot="name">hello</p> 
    <!-- 或者使用 template 标签 v-slot只能用在template标签上 也可以缩写为#name 不过会被编译成作用域插槽 -->
    <template v-slot:name>
      <p>hello</p>
    </template>
  </child>
</template>

# 作用域插槽

<template>
  <div>
    <slot name="slotName" v-bind='data' title="are you ok"></slot>
  </div>
</template>

<script>
export default {
  data() {
    return {
      data: {
        message: 'hello vue'
      }
    }
  }
}
</script>
  • 调用组件
<template>
  <child>
    <template v-slot:slotName="{ message, title }">   //是否是具名的作用域插槽 且v-slot只能使用在组件或者template标签上
      {{ message }}
      {{ title }}
    </template>
  </child>
</template>
<!-- 使用 2.6 更新的写法 -->
<template #slotName="{ message }">
  {{ text }}
</template>
<!-- 默认插槽 -->
<template v-slot="{ text }">
  {{ text }}
</template>