如何在Vuetify中正确地将辅助组件移动到子组件中?

icnyk63a  于 2022-11-17  发布在  Vue.js
关注(0)|答案(1)|浏览(126)

我有一个包含v-card的组件,如下所示:

<!-- CurrentFile.vue -->
<v-card color="primary">
    <v-card-title class="secondary--text text-wrap">Flashing title</v-card-title>
    <v-card-subtitle>
        <span class="secondary--text text-h6">A fancy subtitle</span>
    </v-card-subtitle>
    <v-card-text class="mt-n3">
        ...
    </v-card-text>
</v-card>

在重构时,我希望创建一个新组件来封装v-card-titlev-card-subtitle帮助器组件,因为它们使用相同的文本颜色。

<!-- CurrentFile.vue -->
<v-card color="primary">
    <my-new-header textColor="secondary--text" title="Flashing title" subtitle="A fancy subtitle"/>
    <v-card-text class="mt-n3">
        ...
    </v-card-text>
</v-card>

我接着创建了这个子组件

<!-- MyNewHeader.vue -->
<template>
    <span>
        <v-card-title class="text-wrap" :class="textColor">{{ title }}</v-card-title>
        <v-card-subtitle>
            <span class="text-h6" :class="textColor">{{ subtitle }}</span>
        </v-card-subtitle>
    </span>
</template>

问题

由于包含了一个<span>标记,v-card-titlev-card-subtitle组件的使用几乎是无关紧要的。在我看来,这两个容器都失去了它们的属性(边距和填充)。
当然,这是合乎逻辑的,因为它添加了不希望的层次结构级别。

<v-card>
    <span>
        <v-card-title/>
        <v-card-subtitle>
            <span/>
        </v-card-subtitle>
    </span>
    <v-card-text/>
</v-card>

我非常希望删除<span>标记以避免所有这些问题,但是模板根必须只有一个元素。
有没有其他的方法来做我想做的事情,我错过了?或者也许是过度的想要这么多的子组件?

xxb16uws

xxb16uws1#

您的问题有3种可能的解决方案:
1.使用片段-https://github.com/privatenumber/vue-frag
1.使用render函数而不是组件模板-https://v2.vuejs.org/v2/guide/render-function.html
1.使用CSS display: contents有效地将 Package 器替换为其内容-https://developer.mozilla.org/en-US/docs/Web/CSS/display-box

相关问题