【问题标题】:How to make a component use v-for have dynamic slots如何使组件使用 v-for 具有动态插槽
【发布时间】:2019-11-08 21:25:09
【问题描述】:

我有一个使用 v-for 的子组件。我希望能够让父级传递一个插槽,或者类似于它希望 v-for 显示中的每个项目的方式。但是,问题在于父级在渲染时无法访问 v-for 中的每个单独项目。

我尝试过的一些事情是传递一个带有特定键的插槽。例如

<child-comp :items="items">
    <div v-text="item.text" slot="body"/>
</child-comp>

我正在尝试的基本代码可能看起来像这样(尽管它不起作用)

父组件看起来像

<template>
   <child-comp :items="items>
     <div v-text="item.text"
    </child-comp>
</template>
items = [{ text: 'hello'}]

孩子看起来像这样

<template>
  <div>
     <span v-for="item in items">
       <slot></slot>
     </span>
  </div>
</template>

请注意,这必须是动态的,因为一个项目可能会做 v-text,另一个可能会做一些事情,比如添加更多的 html,例如图像,而另一个项目可能会做一些完全不同的事情。

【问题讨论】:

    标签: vue.js dynamic components v-for


    【解决方案1】:

    我相信您正在寻找作用域插槽。

    https://vuejs.org/v2/guide/components-slots.html#Scoped-Slots

    请注意,使用作用域插槽的首选语法在 Vue 2.6.0 中发生了变化,因此您编写它的确切方式将取决于您使用的版本。

    您的孩子会将item 传递给插槽,如下所示:

    <template>
      <div>
        <span v-for="item in items">
          <slot :item="item"></slot>
        </span>
      </div>
    </template>
    

    对于 Vue 2.6.0+,父级看起来像这样:

    <template>
      <child-comp :items="items">
        <template v-slot:default="slotProps">
          <!-- The parent can put whatever it needs here -->
          {{ slotProps.item }}
        </template>
      </template>
      </child-comp>
    </template>
    

    孩子传递给插槽的任何道具都将包含在slotProps中。无需将其称为 slotProps,实际上它通常是解构的(有关详细信息,请参阅文档)。

    对于 Vue 2.5,您可以改用 slot-scope

    <template>
      <child-comp :items="items">
        <template slot-scope="slotProps">
          <!-- The parent can put whatever it needs here -->
          {{ slotProps.item }}
        </template>
      </template>
      </child-comp>
    </template>
    

    在 Vue 2.5.0 之前,slot-scope 被称为 scope

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-06
      • 1970-01-01
      • 2020-12-26
      • 1970-01-01
      • 2021-05-10
      • 2020-01-01
      相关资源
      最近更新 更多