Search code examples
vue.jsvuejs2vuexvuejs3

How to add a class on the interface based on the condition of the returned data in VueJS


Interface :

enter image description here

How when the index of the returned record is an even number the Row-reverse class is added ?


Solution

  • You can simply achieve that by binding a class attribute dynamically in the element based on the JS expression.

    :class="index % 2 == 0 ? 'product row-reverse' : 'product'"
    

    Live Demo :

    new Vue({
      el: '#app',
      data: {
        items: ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5', 'Item 6']
      }
    })
    .row-reverse {
      background-color: yellow;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="app">
      <li :class="index % 2 == 0 ? 'product row-reverse' : 'product'" v-for="(item, index) in items" :key="index">{{ item }}</li>
    </div>