如何在 VueJS 模板中声明具有动态名称和动态组件的插槽列表? [英] How to declare a list of slots with dynamic names and dynamic components in a VueJS template?
问题描述
假设我有一个包含数据的组件:
Suppose I have a component with data:
data: function () {
return {
slots: [
{ Id: 1, slotName: 'apple', componentName: 'Apple' },
{ Id: 2, slotName: 'banana', componentName: 'Banana' }
]
}
}
并且我想将插槽列表作为作用域插槽传递给子组件.以下语法不起作用,因为您不能在模板元素上使用 v-for:
and I want to pass the list of slots as scoped slots to a child component. The following syntax won't work because you cannot use v-for on a template element:
<child-component>
<template v-for="slot in slots" :key="slot.Id" v-slot[slot.slotName]="slotProps">
<component :is="slot.componentName" :someProp="slotProps"></component>
</template>
</child-component>
并且以下语法将不起作用,因为在 Vue 2.6.0+ 任何未包含在 中的内容假设使用 v-slot 用于默认插槽
.
and the following syntax won't work because in Vue 2.6.0+ any content not wrapped in a <template> using v-slot is assumed to be for the default slot
.
<child-component>
<component v-for="slot in slots" :key="slot.Id"
:is="slot.componentName" v-slot[slot.slotName]="slotProps" :someProp="slotProps"></component>
</child-component>
以下将工作,但编译器会抛出警告并使用不推荐使用的语法:
The following will work but the compiler throws a warning and it uses deprecated syntax:
<child-component>
<component v-for="slot in slots" :key="slot.Id"
:is="slot.componentName" :slot="slot.slotName" slot-scope="slotProps" :someProp="slotProps"></component>
</child-component>
有没有办法使用未弃用的 Vue 模板语法而不使用渲染函数来实现这一点?
Is there any way to achieve this using non-deprecated Vue template syntax and without using a render function?
推荐答案
你只需要在component
上指定key
即可.
You just need to specify the key
on the component
.
<child-component>
<template v-for="slot in slots" v-slot:[slot.slotName]="slotProps">
<component :key="slot.Id" :someProp="slotProps"></component>
</template>
</child-component>
这篇关于如何在 VueJS 模板中声明具有动态名称和动态组件的插槽列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!