javascript - Vue JS - 有条件地在一个组件中显示信息

标签 javascript html vue.js vuejs2

我有一个组件可以 react 性地显示对象数组中包含的数据。目前,该组件显示两个对象,但我希望它根据条件显示一个。如何根据名为 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',
        },
      ]
    }),

最佳答案

您可以在 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" />

编辑: 另一种解决方案是使用 computedmounted Hook 。

computed () {
    this.item = this.premiumActivated ? premiumContent[1] : premiumContent[0]
}

关于javascript - Vue JS - 有条件地在一个组件中显示信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66734860/

相关文章:

javascript - JS 使用新键创建一个新的对象数组

javascript - 我是否很好地使用了 Promise?

javascript - Bootstrap 滚动时固定导航栏在顶部

html - 我用于隐藏元素的 CSS 媒体查询在我的 HTC ONE M8 上不起作用

javascript - 如何在 Firebase 9 中管理 GoogleAuthProvider、signInWithEmailAndPassword 和 setPersistence?

javascript - 自更新至 0.10.4 以来 sails 升力错误

javascript - 为什么我收到 ReferenceError : Response is not defined?

javascript - 如何在网站的菜单页面上添加 3d Logo ?

javascript - 隐藏子组件Vue中的主div

javascript - Vue获取输入框值的方法