【问题标题】:v-if and v-else inside of v-for for different text renderingv-for 中的 v-if 和 v-else 用于不同的文本渲染
【发布时间】:2017-07-26 20:53:59
【问题描述】:

我找不到在 v-for 中选择不同选项来呈现文本的方法。是否有可能或者我需要以不同的方式构造逻辑来执行以下代码之类的操作?

<template>
    <ul v-show="showNotifications">
        <li v-for="notification in notifications">
            // if notification.type = 'friend request'
            New friend request from {{ notification.name }}
            // else 
            New notification from {{ notification.name }}
        </li>
    </ul>
</template>

Notification 是一个包含名称和通知类型等数据的对象数组。

【问题讨论】:

    标签: vuejs2


    【解决方案1】:

    使用另一个template 元素,如下所示(未测试)

    <template>
        <ul v-show="showNotifications">
            <li v-for="notification in notifications">
                <template v-if="notification.type == 'friend request'">
                New friend request from {{ notification.name }}
                </template>
                <template v-else>
                New notification from {{ notification.name }}
                </template>
           </li>
       </ul>
    

    【讨论】:

      【解决方案2】:

      我按照 Xymanek 所说的做了,但这并不完全适合我,我还添加了一个这样的方法,因为我意识到组件对“v-for”中的变量是反应性的,在这种情况下是“通知”

      forceReload(){
            this.files.push(fakeNotification);
            this.files.pop();
          }
      

      正如所见,这只是通过将假对象推送到数组来强制 v-for “重新渲染”。 你可以在“notification.type”的值改变后调用这个方法。

      【讨论】:

      • 您好,如果您有具体问题,请点击Ask a Question 向社区提问。如果您需要对其他用户已经给出的答案的进一步解释,请通过adding a comment 进行此操作。然后,用户将收到一条通知,您对他/她的回答发表了评论
      猜你喜欢
      • 2018-08-16
      • 2021-11-25
      • 1970-01-01
      • 2021-08-01
      • 1970-01-01
      • 2021-02-28
      • 1970-01-01
      • 2018-04-04
      • 2022-01-01
      相关资源
      最近更新 更多