首页 > 解决方案 > 在 Vue 中跨组件共享模板

问题描述

因此,我将 Vue 与 Vuetify 一起使用,并且我有一些非常相似的组件,但差异足以证明将它们分开的组件是合理的。

为了避免重复代码,我创建了一个基础组件,它们扩展了它们以共享它们共同的脚本。但在这种情况下,它们的模板都是完全相同的。像这样的东西:

<v-card class="mb-3">
    <v-card-text>
        <v-form>
            <v-textarea
                v-model="question.text"
                label="Question"
                :auto-grow=true
                rows="1"
                required
                v-if="!options.richText"
            >
                <template slot="append">
                    <v-icon
                            @click="toggleVariable('richText')"
                            v-if="!options.richText"
                            title="Advanced text editor"
                    >format_color_text</v-icon>
                </template>
            </v-textarea>
            <tinymce v-model="question.text" v-if="options.richText"></tinymce>
            <answer
                v-for="(answer, answerIndex) in question.answers"
                :key="answer.id"
                v-on:remove-answer="removeAnswer(answerIndex)"
                :options="options"
                :config="question.config"
                :answer-index="answerIndex"
                :answer="answer"
                :numAnswers="question.answers.length"
            ></answer>
        </v-form>
    </v-card-text>
    <question-options
        :options="options"
        :config="question.config"
        :questionIndex="questionIndex"
        v-on:add-answer="addAnswer"
        v-on:toggle-variable="toggleVariable"
    ></question-options>
</v-card>

什么是允许所有三个组件共享同一个模板的好方法?

我玩弄了scoped slot的想法,但是,如果我理解正确的话,整个模板必须与对所有变量和函数的引用一起放入父组件中。然后我必须在所有想要使用这些子组件的父组件中重复这一点。

我可以做些什么来避免在所有类似的组件中重复所有这些代码?

标签: templatesinheritancevue.jsvuejs2

解决方案


推荐阅读