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

use*_*803 34 components wrapper vue.js vue-component

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

<wrapper>
   <b-table v-bind="$attrs" v-on="$listeners"></b-table>
</wrapper>
Run Code Online (Sandbox Code Playgroud)

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

Dec*_*oon 52

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>
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

渲染功能

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)
  ])
}
Run Code Online (Sandbox Code Playgroud)

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

  • 当使用命名槽(在 vue 2.6.11 上)时,“V​​ue 2.6”的答案对我不起作用。如果我删除部分 `="scope"` 和 `v-bind="scope"`,它适用于命名插槽,但我不能再将它用于作用域插槽:( (2认同)

Pau*_*ski 47

我一直在自动使用任何(和所有)插槽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>
Run Code Online (Sandbox Code Playgroud)

  • 这应该是公认的解决方案。非常干净的解决方案,谢谢! (7认同)

小智 14

这是 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>
Run Code Online (Sandbox Code Playgroud)


小智 9

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

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