【问题标题】:How to declare a list of slots with dynamic names and dynamic components in a VueJS template?如何在 VueJS 模板中声明具有动态名称和动态组件的插槽列表?
【发布时间】: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 &lt;template&gt; 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 注入。每个插槽都需要它们。

标签: vue.js vuejs2


【解决方案1】:

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>

【讨论】:

    【解决方案2】:

    我必须动态生成插槽名称。根据@EzequielFernandez 的回答,我使用了一个函数:

    <template v-for="locale in locales" v-slot:[getSlotName(locale)]="slotProps">
     ...
    </template>
    
    data() {
      return {
        locales: ['en', 'fr']
      }
    },
    methods: {
      getSlotName(locale) {
        return `locale-${locale}`
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-06-30
      • 2017-02-24
      • 1970-01-01
      • 1970-01-01
      • 2019-11-08
      • 2016-03-08
      • 2021-06-30
      • 2014-11-23
      • 2018-10-20
      相关资源
      最近更新 更多