在Vue.js中,如果满足条件则有条件地显示标签而不重复代码

in Vue.js, conditionally display tags if a condition is met without repeating code

首先,我是 Vue 的新手,如果答案很明显,我深表歉意。我有一个用 Vue.js 渲染的元素列表,其中一些项目有一个 "Sold" 属性,当它们有它时,布局必须稍微改变一下,到目前为止效果很好:

<template v-if="property.sold === 'sold'">
    <span class="property-item-sold">{{ property.sold }}</span>
    <div class="item-meta">
        <h3 class="property-item-title">{{ property.name }}</h3>
        <div class="item-meta-group">
            <div class="location"><i class="fas fa-map-marker-alt"></i> {{ property.location | cityState }} {{ property['property-state'][0].name }}</div>
            <div class="size">{{ property.surface.value | numberFormat }} {{ property.surface.unit }}</div>
        </div>
    </div>
</template>

<template v-else>
    <div class="property-item-offering-type">For {{ property['offering-type'][0].name }} </div>
    <div class="item-meta">
        <h3 class="property-item-title">{{ property.name }}</h3>
        <div class="item-meta-group">
            <div class="location"><i class="fas fa-map-marker-alt"></i> {{ property.location | cityState }} {{ property['property-state'][0].name }}</div>
            <div class="size">{{ property.surface.value | numberFormat }} {{ property.surface.unit }}</div>
        </div>
        <a :href="property.url" class="btn btn--green">View Details</a>
    </div>
</template>

但是我重复了很多代码,有没有办法干掉这个条件?

像这样:

<template>
    <span v-if="property.sold === 'sold'" class="property-item-sold">{{ property.sold }}</span>
    <div v-else class="property-item-offering-type">For {{ property['offering-type'][0].name }} </div>
    <div class="item-meta">
        <h3 class="property-item-title">{{ property.name }}</h3>
        <div class="item-meta-group">
            <div class="location"><i class="fas fa-map-marker-alt"></i> {{ property.location | cityState }} {{ property['property-state'][0].name }}</div>
            <div class="size">{{ property.surface.value | numberFormat }} {{ property.surface.unit }}</div>
        </div>
        <a v-if="property.sold !== 'sold'" :href="property.url" class="btn btn--green">View Details</a>
    </div>
</template>