【问题标题】:Use fallback content of slot only if condition is met仅在满足条件时才使用插槽的后备内容
【发布时间】:2019-12-17 17:25:11
【问题描述】:

我想知道是否有办法做我在下面描述的事情:

假设我们有一个带有插槽的组件,并且已经定义了一个后备内容。

在其他地方使用这个组件时,我希望有以下行为:

<TheComponent>
  <template v-slot:name="{ data }">
    <fallback v-if="condition(data)"/>
  </template>
</TheComponent>

我想fallback 标签(或类似标签)不存在(至少,我没有找到它......)。所以我想我想错了,但我找不到解决问题的方法。

问题是我无法更改 TheComponent,因为它是由外部库提供的,我不想重新创建内容。

如果它可以提供帮助,事实上,我正在尝试隐藏展开按钮以防止在 Vuetify data-table 中展开一行,具体取决于该行在展开部分中是否有要显示的内容。所以我想写一些类似的东西:

<v-data-table :items="items" show-expand ...>
  <template v-slot:item.data-table-expand="{ item }">
    <!-- Here I want the default behavior only if my item respects some condition -->
    <fallback v-if="condition(item)"/>
    <!-- Otherwise, I don't want to display the button that expands the row -->
  </template>
</v-data-table>

提前感谢您的帮助。

【问题讨论】:

    标签: vue.js vuejs2 vuetify.js v-slot


    【解决方案1】:

    经过大量“谷歌搜索”后,我认为这是不可能的。恕我直言,您最好的选择是复制 Vuetify 生成的默认插槽内容并将其置于您自己的条件下(在我的示例中为v-if="item.description"):

        <v-data-table :headers="headers" :items="people" show-expand>
          <template v-slot:expanded-item="{ item, headers }">
            <td :colspan="headers.length">{{ item.description }}</td>
          </template>
          <template v-slot:item.data-table-expand="{ item, isExpanded, expand }">
            <v-icon
              v-if="item.description"
              :class="['v-data-table__expand-icon', { 'v-data-table__expand-icon--active': isExpanded }]"
              @click.stop="expand(!isExpanded)"
            >$expand</v-icon>
          </template>
        </v-data-table>
    

    我知道这个解决方案很脆弱,并且随时可能在 Vuetify 更改某些内容时中断,但我认为现在没有更好的解决方案......

    Example

    【讨论】:

    • 非常棒的代码!非常感谢,帮了大忙。 |可以将类似的漂亮(动画)按钮放在标题(在同一列中,行扩展器所在的位置)具有“全部展开”和“全部折叠”的作用,如下所示:codepen.io/打喷嚏/笔/GRggXwp
    • @szabozoltan 您可以使用header.data-table-expand 插槽轻松做到这一点。请参阅我更新的示例...
    • 太棒了!这段代码是一座金矿……真的非常感谢!
    猜你喜欢
    • 2018-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-21
    • 2011-05-13
    • 2013-06-11
    • 1970-01-01
    • 2021-08-25
    相关资源
    最近更新 更多