Vue插槽

91 阅读1分钟

匿名插槽

在子组件中定义插槽

<template>
  <slot></slot>
</template>

在父组件中填充内容

<Son>
    我是匿名
</Son>

具名插槽

在子组件中声明name定义具名插槽

<template>
  <slot name="first"></slot>
</template>

在父组件来将内容插入到子组件对应的插槽中,还可以通过#来代替v-slot:`

<Son>
  <template #first> 我是具名插槽 </template>
</Son>

作用域插槽

在子组件中绑定属性

<template>
  <slot name="last" :son="son"></slot>
</template>

<script>
import { ref } from 'vue'
export default {
  setup() {
    const son = ref('我是子组件')
    return { son }
  }
}
</script>

在父组件中接收数据,或者也可以解构数据

<Son>
    <template #last="props"> 我是作用域插槽 {{ props.son }}</template>
    <template #last="{ son }"> 我是作用域插槽 {{ son }}</template>
</Son>