vue插槽传递

472 阅读1分钟

2.1.0 - 2.6.0

<!-- 作用域插槽 -->
<template v-for="(item) in Object.keys($scopedSlots)" :slot="item" slot-scope="scope">
  <slot :name="item" v-bind="scope || {}"></slot>
</template>

<!-- 具名插槽 -->
<template v-for="(item) in Object.keys($slots)" :slot="item">
  <slot :name="item"></slot>
</template>

2.6.0 -3.0.0

$slots整合到$scopedSlots中了

<template v-for="(item) in Object.keys($scopedSlots)" :slot="item" slot-scope="scope">
  <slot :name="item" v-bind="scope || {}"></slot>
</template>

^3.0.0

注意slots的绑定语法有改变

<template v-for="(item,index) in Object.keys($slots)" v-slot:[item]="scoped" :key="index">
      <slot :name="item" v-bind="scoped || {}"></slot>
    </template>

要注意2.6.0版本后,v-bind动态绑定属性时,要兼容一下当scoped为空对象时; 当非作用域插槽进去的代码遇到Cannot read properties of null (reading 'xxx')这样的报错,基本就是因为内部传递插槽,绑定属性时没有做空对象的处理

jsx语法的就不写了,vue官网就有教程