假设我有一个包含数据的组件:

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>

以下will个选项可以工作,但编译器会抛出警告,并使用不推荐的语法:

<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模板语法而不使用渲染功能来实现这一点?

推荐答案

You can use v-for into a template component

你只需要在component上指定key.

<child-component>
  <template v-for="slot in slots" v-slot:[slot.slotName]="slotProps">
    <component :key="slot.Id" :someProp="slotProps"></component>
  </template>
</child-component>

Vue.js相关问答推荐

为什么 Pinia/Vuex 比使用服务类的classic 方法更受欢迎?

是否可以使用 Vuetify/VueJS 为轮播设置默认图像而不是第一个图像?

如何解决 importers[path] is not a function for clean Vue 3/Vite/Storybook installation

在 Vue 中更改 json 数据后,如何在屏幕上重新呈现表格组件?

是否可以将 nuxt3 与类星体框架一起使用

Svelte 中的简单react 性实验以意想不到的方式失败了. Vue 等效项没有

何时将代码拆分为 Nuxt 中的组件?

将初始值设置为可直接在 HTML 中使用的 vue.js 模型

CssSyntaxError 使用 Webpack 4 构建未知单词

如何在 vue 路由中导航到 Bootstrap-vue 选项卡中的特定选项卡?

云Firestore保存额外的用户数据

Vue:如何将 store 与组件一起使用?

Vue-test-utils:在单个测试中多次使用 $nextTick

Vuetify 输入自动完成错误

正确的 vueJS 方法将props与数据同步

Vue.js 处理多次点击事件

我可以避免使用 Vue.js 组件的重复样式吗?

Jest错误找不到模块....

无法访问函数内的数据属性

在 Vue.js 模板中调用函数