Skip to main content

谈谈 slot

是什么

solt 是插槽的意思,在组件模板中进行占位,当使用该组件标签时候,组件标签里面的内容就会自动替换组件模板中 slot 位置.

分类

slot 可以分来以下三种:

  • 默认插槽(单个)
  • 具名插槽(多个)
  • 作用域插槽(子传父)

默认插槽(单个插槽)

父组件 App.vue

<Child>
<div>默认插槽</div>
</Child>

组件 Child.vue

<template>
<slot>
插槽后备的内容
</slot>
</template>

具名插槽(多个插槽)

  1. 父组件中在使用时在默认插槽的基础上加上 v-slot:(简写:#)属性,值为子组件插槽 name 属性值
  2. 子组件用 name 属性来表示插槽的名字,不传为默认插槽

父组件 App.vue

<Child>
<div v-slot:default>具名插槽</div>
<!-- 具名插槽⽤插槽名做参数 -->
<div v-slot:content>内容...</div>
</Child>

子组件 Child.vue

<template>
<slot>插槽后备的内容</slot>
<slot name="content">插槽后备的内容</slot>
</template>

作用域插槽(子传父)

  1. 父组件中在使用时通过 v-slot:(简写:#)获取子组件的信息,在内容中使用
  2. 子组件在作用域上绑定属性来将子组件的信息传给父组件使用,这些属性会被挂在父组件 v-slot 接受的对象上

父组件

<Child>
<!-- 把v-slot的值指定为作⽤域上下⽂对象 -->
<template #default="slotProps">
来⾃⼦组件数据:{{slotProps.testProps}}
</template>

</Child>

子组件 Child.vue

<template>
<slot name="footer" testProps="子组件的值">
<h3>没传footer插槽</h3>
</slot>
</template>