Search code examples
vue.jsdynamicv-for

Looping in Vue and adding dynamic className


I am quite new to Vue and I have an issue. I have an array of objects and I want the wrapper of the loop to have dynamic className For example

<div v-for="({time, date, name}, i) in myObject" :key="i" class="my-custom-class">

well, if the key (i) is greater than 3 then I want the className to have a different name or at least to add an extra name (like hiddenDiv).

I know is not possible to add the v-if condition in the v-for statement. Any help is appreciated.


Solution

  • Another way of doing this using computed property...

    <div v-for="({time, date, name}, i) in myObject"
    :key="i" :class="getClassName(i)" class="my-custom-class" >
    

    and in your computed

    computed: {
    
     getClassName() {
      return i => {
         if(i === 0) return 'classOne';
         elseif(i === 1) return 'classTwo'
         else return 'classThree';
        // In this way you can maintain as many classNames you want based on the condition
      }
     }
    }