Vue - 如何在包装组件内传递插槽?



所以我创建了一个简单的包装器组件,其中包含如下模板:

<wrapper>
<b-table v-bind="$attrs" v-on="$listeners"></b-table>
</wrapper>

使用$attrs$listeners来传递道具和事件。
工作正常,但是包装器如何将<b-table>命名的插槽代理给子插槽?

Vue 3

与下面的 Vue 2.6 示例相同,除了:

  • $listeners已合并到$attrsv-on="$listeners"因此不再需要。请参阅迁移指南。
  • $scopedSlots现在只是$slots.请参阅迁移指南。

Vue 2.6(V-插槽语法(

所有普通槽都将添加到作用域槽中,因此您只需执行以下操作:

<wrapper>
<b-table v-bind="$attrs" v-on="$listeners">
<template v-for="(_, slot) of $scopedSlots" v-slot:[slot]="scope"><slot :name="slot" v-bind="scope"/></template>
</b-table>
</wrapper>
>Vue 2.5

请看保罗的回答。

<小时 />

原答案

您需要像这样指定插槽:

<wrapper>
<b-table v-bind="$attrs" v-on="$listeners">
<!-- Pass on the default slot -->
<slot/>
<!-- Pass on any named slots -->
<slot name="foo" slot="foo"/>
<slot name="bar" slot="bar"/>
<!-- Pass on any scoped slots -->
<template slot="baz" slot-scope="scope"><slot name="baz" v-bind="scope"/></template>
</b-table>
</wrapper>
>渲染函数
render(h) {
const children = Object.keys(this.$slots).map(slot => h('template', { slot }, this.$slots[slot]))
return h('wrapper', [
h('b-table', {
attrs: this.$attrs,
on: this.$listeners,
scopedSlots: this.$scopedSlots,
}, children)
])
}

您可能还希望在组件上将inheritAttrs设置为 false。

我一直在使用v-for自动传递任何(和所有(插槽,如下所示。这种方法的好处是你不需要知道必须传递哪些插槽,包括默认插槽。传递到包装器的任何插槽都将传递。

<wrapper>
<b-table v-bind="$attrs" v-on="$listeners">
<!-- Pass on all named slots -->
<slot v-for="slot in Object.keys($slots)" :name="slot" :slot="slot"/>
<!-- Pass on all scoped slots -->
<template v-for="slot in Object.keys($scopedSlots)" :slot="slot" slot-scope="scope"><slot :name="slot" v-bind="scope"/></template>
</b-table>
</wrapper>

这是 vue>2.6的更新语法,带有作用域插槽和常规插槽,谢谢 Nikita-Polyakov,链接到讨论

<!-- 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>

此解决方案适用于 Vue 3.2 及以上版本

<template v-for="(_, slot) in $slots" v-slot:[slot]="scope">
<slot :name="slot" v-bind="scope || {}" />
</template>

最新更新