13

I can't find a way to choose different options for rendering text inside of v-for. Is it possible or do I need to structure the logic differently to do something like the code below?

<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 is a array of objects with data like name and notification type.

stefansixx1
  • 256
  • 1
  • 2
  • 11

2 Answers2

28

Use another template element like following (not tested)

<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>

Xymanek
  • 1,357
  • 14
  • 25
0

I did what Xymanek said and that isn't work for me completely, I also added a method like this since I realize the component is reactive to the variable in "v-for", in this case "notifications"

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

as can see this just force the v-for to "re-render" by pushing a fake object to the array. you can call this method just after the value of "notification.type" change.

men32z
  • 186
  • 4
  • 10
  • 1
    Hi, if you have a specific problem, ask the community by hitting [Ask a Question](https://stackoverflow.com/questions/ask). If you need a further explanation for an answer that was already given by an other user, do this by [adding a comment](https://stackoverflow.com/questions/42634908/v-if-and-v-else-inside-of-v-for-for-different-text-rendering#). The user will then get a notification, that you commented on his/her Answer – user3469811 Apr 18 '19 at 18:58