[Vuejs]-Dynamically change the class name Vue

0👍

As per my understanding, You have a set of messages in a chat window and you want to add styles to make differentiate between messages you sent and the messages you received from other person. If Yes, you can directly do that in template itself without any separate method/computed property.

Live Demo :

new Vue({
  el: '#app',
  data: {
    msg: {
        itemList: [{
        messageId: 1,
        userId: 1,
        text: 'Hi'
      }, {
        messageId: 2,
        userId: 2,
        text: 'Hello'
      }, {
        messageId: 3,
        userId: 1,
        text: 'How are you ?'
      }]
    }
  }
})
.chat-item-me {
  background-color: green;
}

.chat-item-stranger {
  background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div
        v-for="message in msg.itemList"
        :key="message.messageId"
        v-bind:class="message.userId === 1 ? 'chat-item-me' :  'chat-item-stranger'" 
      >
      {{ message.text }}
  </div>
</div>

Leave a comment