【问题标题】:Vue JS - Conditionally show the information in one componentVue JS - 有条件地在一个组件中显示信息
【发布时间】:2021-03-21 16:33:04
【问题描述】:

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

【问题讨论】:

    标签: javascript html vue.js vuejs2


    【解决方案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]
    }
    

    【讨论】:

    • 我理解这一切的逻辑,但计算属性不总是期望返回值吗?
    • 是的,对不起,我忘记将返回值添加到计算属性中。
    • 谢谢,只是想澄清一下。但是,我仍然不断收到一个 eslint 错误,指出“在“displayContent”计算属性中出现意外的副作用。”
    • 是的,问题是因为我们正在更新计算属性中的数据对象。我认为解决这个问题的方法可能是使用created 或mounted 钩子或直接使用模板中的计算属性。
    猜你喜欢
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 2021-11-26
    • 2015-03-19
    相关资源
    最近更新 更多