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

时间:2018-06-16 21:23:45

标签: vue.js components vue-component wrapper

所以我用模板创建了一个简单的包装器组件:

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

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

3 个答案:

答案 0 :(得分:32)

我一直在使用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>

答案 1 :(得分:23)

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

请参阅Paul's answer

原始回答

你需要像这样指定插槽:

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

答案 2 :(得分:3)

这是 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>