【问题标题】:Duplicate code in vue.js single file componentvue.js 单文件组件中的重复代码
【发布时间】:2017-02-20 12:39:21
【问题描述】:

在我的一个组件中,模板的某些部分重复了两次。

有可能做这样的事情吗?

<template>
    <div>
        <div v-if='value'>
        *** code here ***
        include 'path_to_file.vue.part'
        </div>
        <div v-else>
        ** another code here ***
        include 'path_to_file.vue.part'
        </div>
    </div>

</template>

【问题讨论】:

  • 你可以创建一个vue组件吗?
  • 是的,我可以,但会很难。我只是想粘贴一些重复的代码。
  • 但是创建一个小组件是处理这个问题的常用方法。是什么让它特别困难?
  • @LinusBorg 没有什么比这更难了,他只是懒惰 :D :D
  • 是时候选择答案了吗?

标签: vue.js vuejs2 vue-component


【解决方案1】:

利用(named) slots:

<slot name="common"></slot>

然后在您“导入”的模板中:

<p slot="common">some</p>

【讨论】:

  • 不,这段代码更难。它包括其他组件。
【解决方案2】:

你可以像这样交替第二个v-if

<template>
    <div>
        <div v-if='value'>
        *** code here ***
        include 'path_to_file.vue.part'
        </div>
        <div v-if='!value'>
        ** another code here ***
        include 'path_to_file.vue.part'
        </div>
    </div>

</template>

【讨论】:

    猜你喜欢
    • 2020-01-02
    • 2011-01-12
    • 2017-11-17
    • 1970-01-01
    • 2017-02-01
    • 2022-08-03
    • 2017-05-04
    • 2018-09-04
    • 2019-05-26
    相关资源
    最近更新 更多