【发布时间】:2019-12-01 01:12:57
【问题描述】:
假设我有一个带有数据的组件:
data: function () {
return {
slots: [
{ Id: 1, slotName: 'apple', componentName: 'Apple' },
{ Id: 2, slotName: 'banana', componentName: 'Banana' }
]
}
}
我想将插槽列表作为作用域插槽传递给子组件。以下语法不起作用,因为您不能在模板元素上使用 v-for:
<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+ 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>
以下将工作,但编译器会抛出警告并使用不推荐使用的语法:
<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 模板语法而不使用渲染函数来实现这一点?
【问题讨论】:
-
可以在模板组件中使用 v-for vuejs.org/v2/guide/list.html#v-for-on-a-lt-template-gt
-
@EzequielFernandez 你是对的!当我尝试这个时,我得到一个编译器错误,关于不允许
key元素,但我们可以改为键入。 -
@DanielElkington 酷!
-
@YomS。道具由
child-component注入。每个插槽都需要它们。