组件作用域插槽分发,将作用域插槽从父组件传递到子组件(Select、FormSelect)

背景

二次封装 Select 组件: src\common\components\Select\index.vue

<template>
  <el-select
    ref="select"
    v-selectdisabled="{ multiple, options, props: curProps, attrs: curAttrs }"
    v-bind="curAttrs"
    v-on="curListeners">
    <!-- 默认的el-option不满足需求时,外部直接通过插槽覆盖 -->
    <slot name="options" :options="options">
      <el-option
        v-for="(item, index) in options"
        :key="customkey ? item[customkey] : index"
        :label="typeof curProps.label === 'function' ? curProps.label(item) : item[curProps.label]"
        :value="typeof curProps.value === 'function' ? curProps.value(item) : item[curProps.value]"
        :disabled="!!item[curProps.disabled]"
        @click.native="handleClickOption(item, index)">
        <slot :item="item" :index="index"></slot>
      </el-option>
    </slot>
  </el-select>
</template>

其中提供了 options 插槽(v-slot:options)和单项n个 option 的插槽(v-slot:default)。

再次进行封装 FormSelect 组件,这里我们需要拿到 Select 内的作用域插槽并往下传递给使用 FormSelect 的组件,最终效果如下:

<FormSelect
  v-model="id"
  :options="users">
  <template v-slot:options="{ options }">
    <el-option v-for="(item, key) in options" :key="key" :value="item.value" :label="`自定义的options ${item.label}`"></el-option>
  </template>
</FormSelect>

image

<FormSelect
  v-model="id"
  :options="users">
  <template v-slot:default="{ item }">自定义的option {{ item.label }}</template>
</FormSelect>

image

问题

如果通过 $slots 这种方式传递,可以传递非作用域插槽,但无法取到插槽的作用域。

<slot v-for="(_, name) in $slots" :name="name" :slot="name" />

解决方案

通过作用域插槽 vm.$scopedSlots 进行传递

<template v-for="(_, name) in $scopedSlots" :slot="name" slot-scope="slotData"><slot :name="name" v-bind="slotData"/></template>

<!-- vue@2.6.0写法 -->
<template v-for="(_, name) in $scopedSlots" v-slot:[name]="slotData"><slot :name="name" v-bind="slotData"/></template>

参考

image

Vue: Pass Slots through from Parent to Child Components

Thanks!

Here is the example in new syntax with customization:

<!-- pass through scoped slots -->
<template v-for="(_, scopedSlotName) in $scopedSlots" v-slot:[scopedSlotName]="slotData">
  <slot :name="scopedSlotName" v-bind="slotData" />
</template>

<!-- pass through normal slots -->
<template v-for="(_, slotName) in $slots" v-slot:[slotName]>
  <slot :name="slotName" />
</template>

<!-- after iterating over slots and scopedSlots, you can customize them like this -->
<template v-slot:overrideExample>
    <slot name="overrideExample" />
    <span>This text content goes to overrideExample slot</span>
</template>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值