所以我创建了一个简单的包装组件,模板如下:
<wrapper>
<b-table v-bind="$attrs" v-on="$listeners"></b-table>
</wrapper>
使用$attrs
和$listeners
传递属性和事件。这很好用,但是包装器如何将<b-table>
命名插槽代理到子项中呢?
所以我创建了一个简单的包装组件,模板如下:
<wrapper>
<b-table v-bind="$attrs" v-on="$listeners"></b-table>
</wrapper>
使用$attrs
和$listeners
传递属性和事件。这很好用,但是包装器如何将<b-table>
命名插槽代理到子项中呢?
Vue 3
与下面的Vue 2.6示例相同,除了以下几点:
<template v-for="(_, slot) of $slots" v-slot:[slot]="scope"><slot :name="slot" v-bind="scope"/></template>
<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的答案。
原始答案
你需要像这样指定插槽:
<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。="scope"
和v-bind="scope"
部分,它可以用于命名插槽,但我不能再用于作用域插槽了:( - pouria我一直在使用 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>
<template v-for="slot in Object.keys($scopedSlots)" :slot="slot" slot-scope="scope"><slot :name="slot" v-bind="scope"/></template>
- JeppePepp这里是更新后的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>
<template v-for="(_, slot) in $slots" v-slot:[slot]="scope">
<slot :name="slot" v-bind="scope || {}" />
</template>
Vue Warn
警告。当我想要包装 Kendo UI Grid 组件并公开其单元格模板插槽时,我遇到了这个问题。 - incutonez[slot]
处遇到了一个TypeScript错误:Element implicitly has an 'any' type because expression of type 'string | number' can't be used to index type {...}
。你有什么解决方法吗? - Gannetimport
您正在包装的组件,即使它已经全局注册。(例如,如果您要包装Quasar的QInput组件,您需要在您的组件中添加import { QInput } from 'quasar'
。) - Partap Davis