Vue JS-有条件地显示一个组件中的信息
2021-03-21
641
我有一个组件,它可以响应式地显示对象数组中包含的数据。目前,该组件显示两个对象,但我希望它根据条件显示其中一个对象。如何根据名为 premiumActivated 的属性的状态显示其中一个对象?
<template>
<div>
<div class="background-div">
<div class="page-info-inner">
<PremiumContent v-for="item in premiumContent"
:key="item.infoText"
:info-text="item.infoText"
:button-text="item.buttonText"
:button-callback="null"
:subscription-text="item.subscriptionText" />
</div>
</div>
</div>
</template>
<script>
import PremiumContent from '../../../components/partials/settings/Premium';
export default {
name: 'MyComponent',
components: {PremiumContent},
data: () => ({
premiumActivated: false,
premiumContent: [
{
infoText: "this is the content that should appear if premiumActivated is false",
buttonText: "button text",
},
{
infoText: "this is the content that should appear if premiumActivated is true",
buttonText: "button text",
subscriptionText: 'extra text',
},
]
}),
1个回答
您可以使用 Vue 中的计算属性来决定需要显示数组中的哪个对象。
computed: {
displayContent () {
return this.premiumActivated ? premiumContent[1] : premiumContent[0]
}
}
您的 PremiumContent 将如下所示:
<PremiumContent
:key="displayContent.infoText"
:info-text="displayContent.infoText"
:button-text="displayContemt.buttonText"
:button-callback="null"
:subscription-text="displayContent.subscriptionText" />
编辑:
另一个解决方案是使用
computed
或
mounted
钩子。
computed () {
this.item = this.premiumActivated ? premiumContent[1] : premiumContent[0]
}
Yash Maheshwari
2021-03-21