Search code examples
javascriptapilaravel-5laravel-5.3vuejs2

Toggle 2 classes on each element of v-for based on conditions


I'm trying to list a list of chats between 2 users with vue 2. in my style, i have 2 classes 'left' and 'right' helping to display if the chat belongs to the first or the last user.

here is my loop

 <div class="row chats-container">
    <div class="row chat-message clearfix" 
        v-for="chat in chats">
        <img src="./../../assets/userDefault.png" alt="">
        <span>{{chat.chat}}</span>
    </div>
 </div>

Here is the condition i want to use : 'v-if="auth.id === chat.sender.id"'

I would like to toggle between two classes : left and right

Need some helps...


Solution

  • You can use property binding on the class attribute like :class and then you can use the properties and methods of your vue-component.

    <div class="row chats-container">
       <div 
           v-for="chat in chats"
           :class='{"row": true, "chat-message": true, "clearfix": true, "left": auth.id !== chat.sender.id, "right": auth.id === chat.sender.id}'
       >
         <img src="./../../assets/userDefault.png" alt="">
         <span>{{chat.chat}}</span>
       </div>
    </div>
    

    If the length of that annoys you (it annoys me), you can setup a method:

    methods: {
      textMessageStyle (chat) {
        return {
          "row": true,
          "chat-message": true, 
          "clearfix": true,
          "left": auth.id !== chat.sender.id, 
          "right": auth.id === chat.sender.id
        }
      }
    }
    

    and then:

    <div class="row chats-container">
       <div 
           v-for="chat in chats"
           :class="textMessageStyle(chat)" 
       >
         <img src="./../../assets/userDefault.png" alt="">
         <span>{{chat.chat}}</span>
       </div>
    </div>