插槽就是子组件中的提供给父组件使用的一个占位符,用 表示,父组件可以在这个占位符中填充任何模板代码,如 HTML、组件等,填充的内容会替换子组件的标签。

匿名插槽

1.在子组件放置一个插槽

  1. <template>
  2. <div>
  3. <slot></slot>
  4. </div>
  5. </template>

父组件使用插槽
在父组件给这个插槽填充内容

  1. <Dialog>
  2. <template v-slot>
  3. <div>2132</div>
  4. </template>
  5. </Dialog>

具名插槽·

具名插槽其实就是给插槽取个名字。一个子组件可以放多个插槽,而且可以放在不同的地方,而父组件填充内容时,可以根据这个名字把内容填充到对应插槽中

  1. <div>
  2. <slot name="header"></slot>
  3. <slot></slot>
  4. <slot name="footer"></slot>
  5. </div>

父组件使用需对应名称

  1. <Dialog>
  2. <template v-slot:header>
  3. <div>1</div>
  4. </template>
  5. <template v-slot>
  6. <div>2</div>
  7. </template>
  8. <template v-slot:footer>
  9. <div>3</div>
  10. </template>
  11. </Dialog>

插槽简写

  1. <Dialog>
  2. <template #header>
  3. <div>1</div>
  4. </template>
  5. <template #default>
  6. <div>2</div>
  7. </template>
  8. <template #footer>
  9. <div>3</div>
  10. </template>
  11. </Dialog>

作用域插槽

在子组件动态绑定参数 派发给父组件的slot去使用

  1. <div>
  2. <slot name="header"></slot>
  3. <div>
  4. <div v-for="item in 100">
  5. <slot :data="item"></slot>
  6. </div>
  7. </div>
  8. <slot name="footer"></slot>
  9. </div>

通过结构方式取值

  1. <Dialog>
  2. <template #header>
  3. <div>1</div>
  4. </template>
  5. <template #default="{ data }">
  6. <div>{{ data }}</div>
  7. </template>
  8. <template #footer>
  9. <div>3</div>
  10. </template>
  11. </Dialog>

动态插槽

插槽可以是一个变量名

  1. <Dialog>
  2. <template #[name]>
  3. <div>
  4. 23
  5. </div>
  6. </template>
  7. </Dialog>
  1. const name = ref('header')