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

Vue - how to pass down slots inside wrapper component?

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

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

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

Vue 3

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

  • $listeners 已合并到 $attrs,因此不再需要 v-on="$listeners"。参见 migration guide.
  • $scopedSlots 现在只是 $slots。参见 migration guide

Vue 2.6(v-slot 语法)

所有普通插槽都会添加到作用域插槽中,因此您只需要这样做:

<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,link to discussion

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